logo资料库

Swift 3 Functional Programming.pdf

第1页 / 共289页
第2页 / 共289页
第3页 / 共289页
第4页 / 共289页
第5页 / 共289页
第6页 / 共289页
第7页 / 共289页
第8页 / 共289页
资料共289页,剩余部分请下载后查看
Cover
Copyright
Credits
About the Author
About the Reviewer
www.PacktPub.com
Table of Contents
Preface
Chapter 1: Getting Started with Functional Programming in Swift
Why functional programming matters?
What is functional programming?
The Swift programming language
Swift features
Modern syntax
Type safety and type inference
Immutability
Stateless programming
First-class functions
Higher-order functions
Pattern matching
Generics
Closures
Subscripts
Optional chaining
Extensions
Objective-C and Swift bridging headers
Automatic Reference Counting
REPL and Playground
Language basics
Type safety and type inference
Type annotation
Type aliases
Immutability
Tuples
Optionals
Basic operators
Strings and characters
Immutability
String literals
Empty Strings
Concatenating strings and characters
String interpolation
String comparison
Collections
Control flows
for loops
while loops
stride
if
switch
guard
Functions
Closures
Map, filter, and reduce
Map
Filter
Reduce
Enumerations
Generics
Classes and structures
Classes versus structures
Choosing between classes and structures
Identity operators
Properties
Property observers
Methods
Subscripts
Inheritance
Initialization
Deinitialization
Automatic Reference Counting
Optionals and optional chaining
Error handling
Type casting
Any and AnyObject
Nested types
Extensions
Protocols
Protocols as types
Protocol extensions
Access control
Summary
Chapter 2: Functions and Closures
What is a function?
The general syntax of functions and methods
Best practices in function definition
Calling functions
Defining and using function parameters
Defining and using variadic functions
Returning values from functions
Pure functions
Function types
Defining and using nested functions
First-class functions
Higher-order functions
Function composition
Custom operators
Allowed operators
Custom operator definition
A composed function with a custom operator
Closures
Closure syntax
Capturing values
Function currying
Recursion
Tail recursion
Memoization
Summary
Chapter 3: Types and Type casting
Value versus reference types
Value and reference type constants
Mixing value and reference types
Copying
Copying reference types
Value type characteristics
Behavior
Isolation
Interchangeability
Testability
Threats
Using value and reference types
Equality versus identity
Equatable and Comparable
Type checking and casting
Summary
Chapter 4: Enumerations and Pattern Matching
Defining enumerations
Associated values
Raw values
Algebraic data types
Simple types
Composite types
Composite type with variants
The algebra of data types
Pattern matching
Patterns and pattern matching
The wildcard pattern
The value-binding pattern
The identifier pattern
The tuple pattern
The enumeration case pattern
The optional pattern
Type casting patterns
The expression pattern
Summary
Chapter 5: Generics and Associated Type Protocols
What are generics and what kind of problems do they solve?
Type constraints
Where clauses
Generic data structures
Associated type protocols
Extending generic types
Subclassing generic classes
Summary
Chapter 6: Map, Filter, and Reduce
Functor
Applicative Functor
Monad
Map
FlatMap and flatten
Filter
Reduce
The map function in terms of reduce
The filter function in terms of reduce
The flatMap function in terms of reduce
The flatten function in terms of reduce
Apply
Join
Chaining higher-order functions
Zip
Practical examples
Sum of an array
Product of an array
Removing nil values from an array
Removing duplicates in an array
Partitioning an array
Summary
Chapter 7: Dealing with Optionals
Optional types
Unwrapping optionals
Force unwrapping
nil checking
Optional binding
Guard
Implicitly unwrapped optionals
Error handling to avoid optionals
try!
try?
Nil-coalescing
Optional chaining
Dealing with optionals functionally
Optional mapping
Multiple optional value mapping
Summary
Chapter 8: Functional Data Structures
Semigroup
Monoid
Trees
Contains
Binary Search Tree
Contains
Size
Elements
Empty
Lists
Empty LinkedList
Cons
Contains
Size
Elements
isEmpty
map, filter, and reduce
Stacks
Lazy list
Summary
Chapter 9: Importance of Immutability
Immutability
Immutable variables
Weak versus strong immutability
Reference types versus value types
The benefits of immutability
Thread safety
Referential transparency
Low coupling
Avoiding temporal coupling
Avoiding identity mutability
Failure atomicity
Parallelization
Exception handling and error management
Caching
State comparison
Compiler optimization
Cases for mutability
An example
Side-effects and unintended consequences
Testability
Copy constructors and lenses
Copy constructor
Lens
Lens composition
Summary
Chapter 10: The Best of Both Worlds – Combining FP Paradigms with OOP
OOP paradigms
Objects
Classes
Inheritance
Overriding
Design constraints
Singleness
Static
Visibility
Composite reuse
Issues and alternatives
When to inherit
Polymorphism
Dynamic binding
OOP design principles
SRP
The FP counterpart
OCP
The FP counterpart
LSP
The FP counterpart
ISP
The FP counterpart
DIP
The FP counterpart
DDD
Concepts
Premise
Building blocks
Aggregate
Immutable value objects
Domain events
Intention-revealing interface
Side-effect-free functions
Assertions
Conceptual contours
Closure of operations
Declarative design
Protocol-oriented programming (POP)
POP paradigms
Protocol composition
Protocol extensions
Protocol inheritance
Associated types
Conforming to a protocol
Functional Reactive Programming (FRP)
Building blocks of FRP
Signals
Pipes
Signal producers
Buffers
Observers
Actions
Properties
Disposables
Schedulers
An example
Mixing OOP and FP
Problems
Granularity mismatch
FP paradigm availability
First-class values
Closures
FP-OOP interrelation tools
FP support
Effects of having FP capabilities in OOP
Idiomatic effects
Architectural effects
OOP design patterns – an FP perspective
Strategy pattern
Command pattern
Observer pattern
Virtual proxy pattern
Visitor pattern
Summary
Chapter 11: Case Study – Developing an iOS Application with the FP and OOP Paradigms
Requirements
High-level design
Frontend
Models
Views
ViewController
State
Store
Actions
Manager
Communication
Communication between layers
Third-party libraries
Cross-cutting concerns
Error management and exception handling
Crash reporting
Analytics
Tools
Backend
Vapor
Routing
JSON
Requesting data
SPM
Backend development
Model
Store
Controller
Posting a new Todo item
Getting a list of Todo items
Getting a specific Todo item
Deleting an item and deleting all Todo items
Updating a Todo item
iOS application development
Configuration
Models
Operators
<^>
<*>
<|
<|?
<||
Using Argo models
ViewModel
Communication
Request protocol
Conforming to a request protocol
WebServiceManager
Creating a Todo item
Listing Todo items
Lens
State
Store
Action
Views
ViewController
MasterViewController
IBActions
TableView Delegates and DataSource
DetailsViewController
Summary
Index
Swift 3 Functional Programming Bring the power of Swift functional programming to iOS, Web, macOS, watchOS and tvOS application development and build clean, smart, scalable and reliable applications Dr. Fatih Nayebi BIRMINGHAM - MUMBAI
Swift 3 Functional Programming Copyright © 2016 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: June 2016 Production reference: 1230616 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78588-388-0 www.packtpub.com
Credits Author Dr. Fatih Nayebi Reviewer Kostiantyn Koval Copy Editor Tasneem Fatehi Project Coordinator Shweta H Birwatkar Commissioning Editor Wilson D'souza Proofreader Safis Editing Acquisition Editors Ruchita Bhansali Reshma Raman Indexer Mariammal Chettiyar Content Development Editor Sumeet Sawant Graphics Disha Haria Technical Editor Manthan Raja Production Coordinator Nilesh Mohite
About the Author Dr. Fatih Nayebi earned his Ph.D. degree in software engineering from École de technologie supérieure, Université du Québec by researching on Mobile Human-Computer Interaction, Software Engineering, and Machine Learning. Fatih has 15 years of industry experience in software engineering and architecture in various fields. He has developed various applications with Visual Basic, C++, C#, Java, MATLAB, Python, Objective-C, and Swift. He is also an enthusiastic Node, Scala, and Haskell developer. His specialties include applied predictive and optimization models, human-computer interaction, functional programming, machine learning, and mobile application architecture and development. Fatih currently works as a Director, Consulting at CGI Group Inc, Montreal, and continues to his academic research and publications as a postdoctoral researcher at École de technologie supérieure. You can find him talking on Swift and Functional Programming at meetups such as h t t p : / / w w w . m e e t u p . c o m / s w i f t - m t l /, on GitHub at h t t p s : / / g i t h u b . c o m / c o n q u e r o r, and on Twitter as @thefatih.
About the Reviewer Kostiantyn Koval is a passionate software engineer with six years of experience. All this while, his main passion and work has been building iOS applications. During this time, he has build many applications, including games, enterprise apps, and big platforms. He fell in love with Swift from the beginning and keeps expressing it by sharing it with the world. Except iOS, he is also interested in other technologies and languages such as Scala, Clojure, LLVM, Ruby, JS, Web, and others. He is also the author of a Swift High Performance book, Packt Publishing. He loves open source and blogging. You can find him on GitHub at h t t p s : / / g i t h u b . c o m / k o s t i a k o v a l, his blogs can be read at h t t p s : / / m e d i u m . c o m / @ k o s t i a k o v a l or h t t p : / / k o s t i a k o v a l . g i t h u b . i o, and his Twitter handle is @KostiaKoval.
www.PacktPub.com For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. h t t p s : / / w w w 2 . p a c k t p u b . c o m / b o o k s / s u b s c r i p t i o n / p a c k t l i b Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books. Why subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browser Free access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Table of Contents Preface Chapter 1: Getting Started with Functional Programming in Swift Why functional programming matters? What is functional programming? The Swift programming language Swift features Modern syntax Type safety and type inference Immutability Stateless programming First-class functions Higher-order functions Pattern matching Generics Closures Subscripts Optional chaining Extensions Objective-C and Swift bridging headers Automatic Reference Counting REPL and Playground Language basics Type safety and type inference Type annotation Type aliases Immutability Tuples Optionals Basic operators Strings and characters Immutability String literals Empty Strings Concatenating strings and characters String interpolation String comparison Collections 1 7 7 9 10 10 11 12 12 12 13 13 13 13 13 13 13 14 14 14 14 14 15 15 16 16 16 17 17 18 18 18 18 19 19 19 19
分享到:
收藏