Swift 3 Functional Programming - Dr. Fatih Nayebi - E-Book

Swift 3 Functional Programming E-Book

Dr. Fatih Nayebi

0,0
38,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Bring the power of Swift functional programming to iOS, Web, macOS, watchOS and tvOS application development and build clean, smart, scalable and reliable applications

About This Book

  • Written for Swift 3 -Developers Preview version, this is a comprehensive guide that introduces iOS and OS X developers to the all-new world of functional programming that has so far been alien to them
  • Learn about first-class functions and how imperative-style patterns can be converted into functional code using some simple techniques
  • The book will get you familiar with using functional programming alongside existing OOP techniques so you can get the best of both worlds and develop clean, robust code

Who This Book Is For

The book is for developers with a basic knowledge of Swift programming aiming to incorporate functional programming paradigms in their day-to-day application development

What You Will Learn

  • First-class, higher-order, and pure functions
  • Closures and capturing values
  • Custom operators, recursion, and memoization
  • Value and reference types in Swift
  • Enumerations, algebraic data types, patterns, and pattern matching
  • Generics and associated type protocols
  • Higher-order functions such as map, flatMap filter, and reduce
  • Dealing with optionals, fmap, and apply for multiple functional mapping
  • Functional data structures such as Semigroup, Monoid, Binary Search Tree, Linked List, Stack, and Lazy List
  • Immutability, copy constructors, and lenses
  • Combining FP paradigms with OOP, FRP, and POP in your day-to-day development activities
  • Developing a backend application with Swift
  • Developing an iOS application with FP, OOP, FRP, and POP paradigms

In Detail

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.

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.

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.

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.

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.

Style and approach

This is an easy-to-follow guide 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.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 323

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Swift 3 Functional Programming
Credits
About the Author
About the Reviewer
www.PacktPub.com
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
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
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
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
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
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
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
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
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
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
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
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

Swift 3 Functional Programming

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 

Copy Editor

Tasneem Fatehi 

Reviewer

Kostiantyn Koval 

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 http://www.meetup.com/swift-mtl/, on GitHub at https://github.com/conqueror, 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 https://github.com/kostiakoval, his blogs can be read at https://medium.com/@kostiakoval or http://kostiakoval.github.io, 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 [email protected] 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.

https://www2.packtpub.com/books/subscription/packtlib

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 PacktCopy and paste, print, and bookmark contentOn 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.

Preface

Functional programming (FP) is getting a lot of attention as it eases many of the difficulties faced in object-oriented programming (OOP), such as testability, maintainability, scalability, and concurrency. Swift has a lot of functional programming features that can be easily used, but most Objective-C and Swift programmers are not familiar with these tools.

This book aims to simplify the functional programming paradigms and make it easily usable for Swift programmers, showing you how to use popular functional programming techniques to solve many of your day-to-day development problems. Whether you are new to functional programming and Swift or experienced, this book will provide you with the skills you need to design and develop high quality, easily maintainable, scalable, and efficient applications for iOS, macOS, tvOS, and watchOS. Through this book, you'll learn to build bug-free, maintainable code using functional programming.

What this book covers

Chapter 1, Getting Started with Functional Programming in Swift, introduces functional programming paradigms, such as immutability, stateless programming, pure, first-class, and higher-order functions. This chapter will provide an introduction to the Swift programming language and functional programming paradigms in Swift.

Chapter 2, Functions and Closures, begins with a definition of functions, continues with other related topics, such as function types and tuples, and finally concludes with more advanced topics such as first-class functions, higher-order functions, function composition, closures, currying, recursion, and memoization.

Chapter 3, Types and Type casting, takes a look at types in general and explores reference versus value types in detail. We will cover topics such as value and reference type constants, mixing value and reference types, and copying. Then we will discuss the characteristics of value types. We will also cover the key differences between value and reference types, and how we should decide which one to use. We will continue by exploring equality, identity, type checking, and casting topics.

Chapter 4, Enumerations and Pattern Matching, explains the enumeration definition and usage. We will cover associated and raw values and introduce the concept of algebraic data types. We will explore some examples to cover the sum, product, and recursion types. Also, in this chapter, we will explore patterns such as wildcard, value-binding, identifier, tuple, enumeration case, optional, type casting, and expression, along with related pattern matching examples.

Chapter 5, Generics and Associated Type Protocols, teaches us how to define and use generics. We will also understand the type of problems generics solve. Moving forward, we will explore type constraints, generic data structures, and associated type protocols with examples.

Chapter 6, Map, Filter, and Reduce, introduces the map, filter, and reduce methods in the Swift programming language with appropriate examples. These methods are used on arrays and can replace almost all uses of for-in loops and are more clear and concise.

Chapter 7, Dealing with Optionals, familiarizes us with different techniques to deal with optionals. We will talk about built-in techniques to deal with optionals, such as optional binding, guard, coalescing, and optional chaining. Then we will explore functional programming techniques to deal with optionals.

Chapter 8, Functional Data Structures, introduces you to the concept of functional data structures and explores examples of data structures implemented in functional way, such as Semigroup, Monoid, BST, LinkedList, Stack, and LazyList.

Chapter 9, Importance of Immutability, explores the concept of immutability. We will look at its importance and benefits with the help of examples. Then we will look into cases for mutability and go through an example to compare mutability and immutability effects on our code.

Chapter 10, The Best of Both Worlds – Combining FP Paradigms with OOP, covers object-oriented programming principles and paradigms. Then we will be introduced to protocol-oriented programming. Next, we will have an introduction of functional reactive programming and explore how to mix FP with OOP paradigms.

Chapter 11, Case Study – Developing an iOS Application with the FP and OOP Paradigms, teaches us to develop a Todo backend and an iOS application, employing the concepts we have discussed so far. We will use functional programming techniques to parse and map the data, we will use functional reactive programming to reactively manage events in applications. We will also employ protocol-oriented programming and object-oriented programming techniques as well.

What you need for this book

To follow along with the examples in this book, you'll need to have an Apple computer with macOS 10.10 or higher installed. You'll also need to install Xcode version 8 beta 1 with Swift 3.0 Preview 1.

Who this book is for

The book is for iOS and macOS developers with basic knowledge of Swift programming. Prior knowledge of object-oriented programming is assumed.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book 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 files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Swift-3-Functional-Programming. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/Swift3FunctionalProgramming_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Chapter 1. Getting Started with Functional Programming in Swift

In this chapter, we will be introduced to functional programming paradigms, such as immutability, stateless programming, pure, first-class, and higher-order functions. This chapter will give an introduction to the Swift programming language and functional programming paradigms in Swift. The following topics will be covered along with examples:

Why functional programming matters?What is functional programming?Swift language basicsImmutabilityFirst-class, higher-order, and pure functionsOptionals and pattern matchingClosuresType aliasing

Why functional programming matters?

Software solutions are becoming complex and it is necessary to structure them very well for future maintenance and extension. Software engineers try to modularize software to smaller pieces and abstract away complexities in different pieces and layers. Dividing the code into smaller pieces makes it possible to tackle each problem individually. This approach improves collaboration because different engineers can take responsibility for different pieces. Also, they can work on specific parts of software without being concerned about the other parts.

Dividing software into smaller pieces is not the biggest challenge in most of the projects and programming languages. For instance, in object-oriented programming (OOP), software is divided into smaller pieces such as packages, classes, interfaces, and methods. Engineers tend to divide the software into these building blocks by domains, logic, and layers. Classes are recipes to create instances and objects. As the name suggests, the most important building blocks in OOP are objects. Engineers deal with objects and the role and responsibility for them should be clear and understandable.

In OOP, connecting the building blocks to each other is not as easy as dividing them. Connection between different objects may propose strong coupling between them. Coupling is the biggest source of complexity in OOP. A change in a module or class could force change in all coupled modules and classes. Also, a particular module or class might be harder to reuse and test because of coupled modules or classes.

Software engineers try to loosen coupling by structuring the software well and applying different principles and design patterns. For instance, single responsibility, open-closed, Liskov substitution, interface segregation and dependency inversion (SOLID) principles when applied together properly tend to make software easy to maintain and extend.

Even though it is possible to decrease the coupling and simplify software structures, managing the memory, referencing to instances, and testing different objects remains difficult because, in OOP, objects are open to change and mutation.

In functional programming, pure functions are the most important building blocks. Pure functions do not rely on data outside of themselves and they do not change data that exists outside of them. Pure functions are easy to test because they will always provide the same results.

Pure functions can be executed on different threads or cores without any mechanisms to handle multithreading and multiprocessing. This is a very important benefit of functional programming over OOP as multicore programming mechanisms are very complex to handle in OOP. Also, programming for multicore computers is becoming more important day by day because hardware engineers have finally hit the speed limit of light. Computer clocks will not be getting faster in the near future so, in order to have more cycles per second, hardware engineers are adding more processors to chips. There seems no end to how many processors we will have in our computers. A higher number of processors to be used for a program means a more complex multithreading and multicore mechanism to handle.

Functional programming eliminates the need for a complex multicore programming mechanism, and as pure functions are not dependent on any instances or data outside of themselves, it is easy to change them without changing other parts.