O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Swift Functional Programming - Second Edition

Book Description

Bring the power of functional programming to Swift to develop clean, smart, scalable and reliable applications.

About This Book

  • Written for the latest version of Swift, this is a comprehensive guide that introduces iOS, Web and macOS developers to the all-new world of functional programming that has so far been alien to them
  • Get familiar with using functional programming alongside existing OOP techniques so you can get the best of both worlds and develop clean, robust, and scalable code
  • Develop a case study on example backend API with Swift and Vapor Framework and an iOS application with Functional Programming, Protocol-Oriented Programming, Functional Reactive Programming, and Object-Oriented Programming techniques

Who This Book Is For

Meant for a reader who knows object-oriented programming, has some experience with Objective-C/Swift programming languages and wants to further enhance his skills with functional programming techniques with Swift 3.x.

What You Will Learn

  • Understand what functional programming is and why it matters
  • Understand custom operators, function composition, currying, recursion, and memoization
  • Explore algebraic data types, pattern matching, generics, associated type protocols, and type erasure
  • Get acquainted with higher-kinded types and higher-order functions using practical examples
  • Get familiar with functional and non-functional ways to deal with optionals
  • Make use of functional data structures such as semigroup, monoid, binary search tree, linked list, stack, and lazy list
  • Understand the importance of immutability, copy constructors, and lenses
  • Develop a backend API with Vapor
  • Create an iOS app by combining FP, OOP, FRP, and POP paradigms

In Detail

Swift is a multi-paradigm programming language enabling you to tackle different problems in various ways. Understanding each paradigm and knowing when and how to utilize and combine them can lead to a better code base. Functional programming (FP) is an important paradigm that empowers us with declarative development and makes applications more suitable for testing, as well as performant and elegant. This book aims to simplify the FP paradigms, making them easily understandable and usable, by showing you how to solve many of your day-to-day development problems using Swift FP.

It starts with the basics of FP, and you will go through all the core concepts of Swift and the building blocks of FP. You will also go through important aspects, such as function composition and currying, custom operator definition, monads, functors, applicative functors,memoization, lenses, algebraic data types, type erasure, functional data structures, functional reactive programming (FRP), and protocol-oriented programming(POP). You will then learn to combine those techniques to develop a fully functional iOS application from scratch

Style and approach

An easy-to-follow guide that is full of hands-on coding examples of real-world applications. Each topic is explained sequentially and placed in context, and for the more inquisitive, there are more details of the concepts used. It introduces the Swift language basics and functional programming techniques in simple, non-mathematical vocabulary with examples in Swift.

Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the code file.

Table of Contents

  1. Preface
    1. What this book covers
    2. What you need for this book
    3. Who this book is for
    4. Conventions
    5. Reader feedback
    6. Customer support
      1. Downloading the example code
      2. Downloading the color images of this book
      3. Errata
      4. Piracy
      5. Questions
  2. Getting Started with Functional Programming in Swift
    1. Why functional programming matters
    2. What is FP?
    3. The Swift programming language
      1. Swift features
        1. Modern syntax
        2. Type safety and type inference
        3. Immutability
        4. Stateless programming
        5. First-class functions
        6. Higher-order functions
        7. Closures
        8. Subscripts
        9. Pattern matching
        10. Generics
        11. Optional chaining
        12. Extensions
        13. Objective-C and Swift bridging headers
        14. Automatic Reference Counting
        15. REPL and Playground
      2. Language basics
        1. Types
        2. Type inference
        3. Type annotation
        4. Type aliases
        5. Type casting
        6. Immutability
        7. Tuples
        8. Optionals
      3. Basic operators
        1. Strings and characters
        2. Immutability
        3. String literals
        4. Empty Strings
        5. Concatenating strings and characters
        6. String interpolation
        7. String comparison
        8. Collections
      4. Control flows
        1. for loops
        2. while loops
        3. The stride functions
        4. if
        5. Switch
        6. Guard
      5. Functions
        1. Closures
        2. The map, filter, and reduce functions
        3. The map function
        4. The filter function
        5. The reduce function
      6. Enumerations
      7. Generics
      8. Classes and structures
      9. Classes versus structures
        1. Choosing between classes and structures
        2. Identity operators
      10. Properties
        1. Property observers
        2. Methods
        3. Subscripts
        4. Inheritance
        5. Initialization
        6. De-initialization
          1. Automatic Reference Counting
        7. Any and AnyObject
        8. Nested types
      11. Protocols
        1. Protocols as types
      12. Extensions
        1. Protocol extensions
      13. Access control
      14. Error handling
    4. Summary
  3. Functions and Closures
    1. What is a function?
    2. Syntax
      1. Best practices in function definition
      2. Calling functions
      3. Defining and using function parameters
      4. Defining and using variadic functions
      5. Returning values from functions
      6. Defining and using nested functions
    3. Pure functions
    4. Function types
    5. First-class functions
    6. Higher-order functions
    7. Function composition
      1. Custom operators
        1. Allowed operators
        2. Custom operator definition
        3. A composed function with custom operator
    8. Closures
      1. Closure syntax
      2. Capturing values
    9. Function currying
    10. Recursion
      1. Tail recursion
    11. Memoization
    12. Summary
  4. Types and Type Casting
    1. Kinds of types
    2. Value versus reference types
      1. Value and reference type constants
      2. Mixing value and reference types
      3. Copying
      4. Copying reference types
      5. Value type characteristics
        1. Behaviour
        2. Isolation
        3. Interchangeability
        4. Testability
        5. Threats
      6. Using value and reference types
    3. Equality versus identity
    4. Equatable and Comparable
    5. Type checking and casting
    6. Summary
  5. Enumerations and Pattern Matching
    1. Defining enumerations
      1. Associated values
      2. Raw values
      3. Nesting and containing enumerations
    2. Algebraic data types
      1. Simple types
      2. Composite types
      3. Composite types with variants
      4. The algebra of data types
    3. Pattern matching
      1. Patterns and pattern matching
        1. The wildcard pattern
        2. The value-binding pattern
        3. The identifier pattern
        4. The tuple pattern
        5. The enumeration case pattern
        6. The optional pattern
        7. Type casting patterns
        8. The expression pattern
    4. Summary
  6. Generics and Associated Type Protocols
    1. What are Generics and what kind of problems do they solve?
    2. Type constraints
      1. The where clauses
    3. Generic data structures
    4. Associated type protocols
    5. Type erasure
    6. Extending Generic types
    7. Subclassing Generic classes
    8. Generics manifesto
    9. Summary
  7. Map, Filter, and Reduce
    1. Higher-kinded types
      1. Functors
      2. Applicative Functors
      3. Monads
    2. The map function
    3. The flatMap method
    4. The filter function
    5. The reduce function
      1. The map function in terms of reduce
      2. The filter function in terms of reduce
      3. The flatMap function in terms of reduce
      4. The flatten function in terms of reduce
    6. The apply function
    7. The join function
    8. Chaining higher-order functions
    9. The zip function
    10. Practical examples
      1. Sum and product of an array
      2. Removing nil values from an array
      3. Removing duplicates in an array
      4. Partitioning an array
    11. Summary
  8. Dealing with Optionals
    1. Optional types
    2. Unwrapping optionals
      1. Force unwrapping
      2. nil checking
      3. Optional binding
    3. Guard
    4. Implicitly-unwrapped optionals
    5. Nil-coalescing
    6. Optional chaining
    7. Dealing with Optionals' functionally
      1. Optional mapping
      2. Multiple optional value mapping
    8. Error handling
      1. try!
      2. try?
    9. Summary
  9. Functional Data Structures
    1. Semigroups
    2. Monoids
    3. Trees
      1. The contains method
      2. Binary Search Trees
        1. The contains method
        2. Size
        3. Elements
        4. Empty
    4. Lists
      1. Empty LinkedList
      2. Cons
      3. Contains
      4. Size
      5. Elements
      6. isEmpty
      7. map, filter, and reduce
    5. Stacks
    6. Lazy lists
    7. Summary
  10. Importance of Immutability
    1. Immutability
    2. Immutable variables
      1. Weak versus strong immutability
    3. Reference types versus value types
    4. Benefits of immutability
      1. Thread safety
      2. Referential transparency
      3. Low coupling
      4. Avoiding temporal coupling
      5. Avoiding identity mutability
      6. Failure atomicity
      7. Parallelization
      8. Exception handling and error management
      9. Caching
      10. State comparison
      11. Compiler optimization
    5. Cases for mutability
    6. An example
      1. Side-effects and unintended consequences
      2. Testability
    7. Copy constructors and lenses
      1. Copy constructors
      2. Lenses
        1. Lens composition
    8. Summary
  11. Best of Both Worlds and Combining FP Paradigms with OOP
    1. OOP paradigms
      1. Objects
      2. Classes
      3. Inheritance
        1. Overriding
      4. Design constraints
        1. Singleness
        2. Static
        3. Visibility
        4. Composite reuse
        5. Issues and alternatives
        6. When to inherit
      5. Polymorphism
      6. Dynamic binding
    2. OOP design principles
      1. SRP
        1. The FP counterpart
      2. OCP
        1. The FP counterpart
      3. LSP
        1. The FP counterpart
      4. ISP
        1. The FP counterpart
        2. DIP
        3. The FP counterpart
      5. DDD
        1. Concepts
        2. Premise
        3. Building blocks
          1. Aggregate
          2. Immutable value objects
          3. Domain events
          4. Intention-revealing interface
          5. Side-effect-free functions
          6. Assertions
          7. Conceptual contours
          8. Closure of operations
          9. Declarative design
    3. POP
      1. POP paradigms
        1. Protocol composition
        2. Protocol extensions
        3. Protocol inheritance
        4. Associated types
        5. Conforming to a protocol
    4. Functional reactive programming
      1. Building blocks of FRP
        1. Events
        2. Signals
        3. Pipes
        4. Signal producers
        5. Observers
        6. Lifetimes
        7. Actions
        8. Properties
        9. Disposables
        10. Schedulers
      2. An example
    5. Mixing OOP and FP
      1. Problems
        1. Granularity mismatch
      2. FP paradigm availability
        1. First-class values
        2. Closures
        3. FP-OOP interrelation tools
      3. FP support
      4. Effects of having FP capabilities in OOP
        1. Idiomatic effects
          1. Code abstraction at a function/method level
          2. Generic iterator operations
          3. Operation compositions and sequence comprehensions
          4. Function partial applications and currying
        2. Architectural effects
          1. Reduction of the number of object/class definitions
          2. Name abstraction at a function/method level
      5. OOP design patterns - a FP perspective
        1. Strategy pattern
        2. Command pattern
        3. Observer pattern
        4. Virtual proxy pattern
        5. Visitor pattern
    6. Summary
  12. Case Study - Developing an iOS Application with FP and OOP Paradigms
    1. Requirements
    2. High-level design
      1. Frontend
        1. Models
        2. Views
        3. ViewController
        4. State
        5. Store
        6. Actions
        7. Manager
        8. Communication
        9. Communication between layers
        10. Third-party libraries/frameworks
        11. Cross-cutting concerns
          1. Error management and exception handling
        12. Tools
      2. Backend
        1. Vapor
          1. Routing
          2. JSON
          3. Request data
        2. SPM
    3. Backend development
      1. Model
      2. Store
      3. Controller
        1. Posting a new Todo item
        2. Getting a list of Todo items
        3. Getting a specific Todo item
        4. Deleting an item and deleting all Todo items
        5. Updating a Todo item
    4. iOS application development
      1. Configuration
      2. Models
        1. Operators
          1. <^> operator
          2. <*> operator
          3. <| operator
          4. <|? operator
          5. <|| operator
        2. Using Argo models
        3. viewModel
      3. Communication
        1. The request protocol
        2. Conforming to the request protocol
        3. WebServiceManager
        4. Creating a Todo item
        5. Listing Todo items
      4. Lenses
      5. States
      6. Store
      7. Actions
      8. Views
      9. ViewControllers
        1. MasterViewController
          1. IBActions
          2. TableView delegates and DataSource
        2. DetailsViewController
    5. Summary