Book Image

Swift 3 Functional Programming

By : Dr. Fatih Nayebi
Book Image

Swift 3 Functional Programming

By: Dr. Fatih Nayebi

Overview of this book

<p>This book is based on Swift 3 Developer preview version and aims at simplifying the functional programming (FP) paradigms making it easily usable, by showing you how to solve many of your day-to-day development problems.</p> <p>Whether you are new to functional programming and Swift or experienced, this book will strengthen the skills you need to design and develop high-quality, scalable, and efficient applications.</p> <p>The book starts with functional programming concepts, the basics of Swift 3, and essential concepts such as functions, closures, optionals, enumerations, immutability, and generics in detail with coding examples.</p> <p>Furthermore, this book introduces more advanced topics such as function composition, monads, functors, applicative functors, memoization, lenses, algebraic data types, functional data structures, functional reactive programming (FRP), protocol-oriented programming (POP) and mixing object-oriented programming (OOP) with functional programming (FP) paradigms.</p> <p>Finally, this book provides a working code example of a front-end application developed with these techniques and its corresponding back-end application developed with Swift.</p>
Table of Contents (17 chapters)
Swift 3 Functional Programming
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface

Practical examples


Let's explore some practical examples of higher-order functions.

Sum of an array

We can use reduce to calculate the sum of a list of numbers as follows:

let listOfNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let sumOfNumbers = reduce(elements: listOfNumbers, initial: 0, combine: +)

print(sumOfNumbers)

The result will be 55, as expected.

Product of an array

We can use reduce to calculate the product of array values as follows:

let productOfNumbers = reduce(elements: listOfNumbers, initial: 1,
  combine: *)

print(productOfNumbers)

The result will be 3628800, as expected.

Removing nil values from an array

We can use flatMap to get values out of optional arrays and remove nil values:

let optionalArray: [String?] = ["First", "Second", nil, "Fourth"]
let nonOptionalArray = optionalArray.flatMap { $0 }

print(nonOptionalArray)

The result will be ["First", "Second", "Fourth"], as expected.

Removing duplicates in an array

We can use...