34,79 €
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
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 342
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 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
Second edition: April 2017
Production reference: 1210417
ISBN 978-1-78728-450-0
www.packtpub.com
Author
Dr. Fatih Nayebi
Copy Editor
Safis Editing
Reviewer
Giordano Scalzo
Project Coordinator
Shweta H Birwatkar
Commissioning Editor
Ashwin Nair
Proofreader
Safis Editing
Acquisition Editor
Dibyajyoti Ghosh
Indexer
Pratik Shirodkar
Content Development Editor
Amrita Noronha
Graphics
Tania Dutta
Technical Editor
Nilesh Sawakhande
Production Coordinator
Aparna Bhagat
Dr. Fatih Nayebi has more than 15 years of industry experience in software engineering and architecture in various fields. He has developed numerous applications with Visual Basic, C++, C#, Java, MATLAB, Python, Objective-C, and Swift. He has been designing and developing enterprise and consumer iOS applications since the release of first iOS SDK. He is also an enthusiastic Node, Scala, and Haskell developer.
Aside from industry, Fatih 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.
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, on Twitter as @thefatih, and on Instagram as @thefatih.
Giordano Scalzo is a developer with 20 years of programming experience, since the days of ZXSpectrum. He has worked in C++, Java, .NET, Ruby, Python and in a ton of other languages he has forgotten the names of. After years of backend development, over the past five years, Giordano has developed extensively for iOS, releasing more than 20 apps, apps that he wrote for clients, enterprise application, or for his own company.
Currently, he is a contractor in London, where, through his company, Effective Code Ltd, http://effectivecode.co.uk, he delivers code for iOS aiming at quality and reliability.
In his spare time, when he is not crafting retro game clones for iOS, he writes his thoughts on http://giordanoscalzo.com.
I’d like to thank my better half, Valentina, who lovingly supports me in everything I do: without you, none of this would have been possible.
Thanks to my bright future, Mattia and Luca, for giving me lots of smiles and hugs when I needed them.Finally, my gratitude goes to my mum and dad, who gave my curiosity and the support to follow my passions, begun one day when they bought me a ZXSpectrum.
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://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787284506.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
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
Getting Started with Functional Programming in Swift
Why functional programming matters
What is FP?
The Swift programming language
Swift features
Modern syntax
Type safety and type inference
Immutability
Stateless programming
First-class functions
Higher-order functions
Closures
Subscripts
Pattern matching
Generics
Optional chaining
Extensions
Objective-C and Swift bridging headers
Automatic Reference Counting
REPL and Playground
Language basics
Types
Type inference
Type annotation
Type aliases
Type casting
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
The stride functions
if
Switch
Guard
Functions
Closures
The map, filter, and reduce functions
The map function
The filter function
The reduce function
Enumerations
Generics
Classes and structures
Classes versus structures
Choosing between classes and structures
Identity operators
Properties
Property observers
Methods
Subscripts
Inheritance
Initialization
De-initialization
Automatic Reference Counting
Any and AnyObject
Nested types
Protocols
Protocols as types
Extensions
Protocol extensions
Access control
Error handling
Summary
Functions and Closures
What is a function?
Syntax
Best practices in function definition
Calling functions
Defining and using function parameters
Defining and using variadic functions
Returning values from functions
Defining and using nested functions
Pure functions
Function types
First-class functions
Higher-order functions
Function composition
Custom operators
Allowed operators
Custom operator definition
A composed function with custom operator
Closures
Closure syntax
Capturing values
Function currying
Recursion
Tail recursion
Memoization
Summary
Types and Type Casting
Kinds of types
Value versus reference types
Value and reference type constants
Mixing value and reference types
Copying
Copying reference types
Value type characteristics
Behaviour
Isolation
Interchangeability
Testability
Threats
Using value and reference types
Equality versus identity
Equatable and Comparable
Type checking and casting
Summary
Enumerations and Pattern Matching
Defining enumerations
Associated values
Raw values
Nesting and containing enumerations
Algebraic data types
Simple types
Composite types
Composite types 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
Generics and Associated Type Protocols
What are Generics and what kind of problems do they solve?
Type constraints
The where clauses
Generic data structures
Associated type protocols
Type erasure
Extending Generic types
Subclassing Generic classes
Generics manifesto
Summary
Map, Filter, and Reduce
Higher-kinded types
Functors
Applicative Functors
Monads
The map function
The flatMap method
The filter function
The reduce function
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
The apply function
The join function
Chaining higher-order functions
The zip function
Practical examples
Sum and product of an array
Removing nil values from an array
Removing duplicates in an array
Partitioning an array
Summary
Dealing with Optionals
Optional types
Unwrapping optionals
Force unwrapping
nil checking
Optional binding
Guard
Implicitly-unwrapped optionals
Nil-coalescing
Optional chaining
Dealing with Optionals' functionally
Optional mapping
Multiple optional value mapping
Error handling
try!
try?
Summary
Functional Data Structures
Semigroups
Monoids
Trees
The contains method
Binary Search Trees
The contains method
Size
Elements
Empty
Lists
Empty LinkedList
Cons
Contains
Size
Elements
isEmpty
map, filter, and reduce
Stacks
Lazy lists
Summary
Importance of Immutability
Immutability
Immutable variables
Weak versus strong immutability
Reference types versus value types
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 constructors
Lenses
Lens composition
Summary
Best of Both Worlds and 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
POP
POP paradigms
Protocol composition
Protocol extensions
Protocol inheritance
Associated types
Conforming to a protocol
Functional reactive programming
Building blocks of FRP
Events
Signals
Pipes
Signal producers
Observers
Lifetimes
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
Code abstraction at a function/method level
Generic iterator operations
Operation compositions and sequence comprehensions
Function partial applications and currying
Architectural effects
Reduction of the number of object/class definitions
Name abstraction at a function/method level
OOP design patterns - a FP perspective
Strategy pattern
Command pattern
Observer pattern
Virtual proxy pattern
Visitor pattern
Summary
Case Study - Developing an iOS Application with FP and OOP Paradigms
Requirements
High-level design
Frontend
Models
Views
ViewController
State
Store
Actions
Manager
Communication
Communication between layers
Third-party libraries/frameworks
Cross-cutting concerns
Error management and exception handling
Tools
Backend
Vapor
Routing
JSON
Request 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
<^> operator
<*> operator
<| operator
<|? operator
<|| operator
Using Argo models
viewModel
Communication
The request protocol
Conforming to the request protocol
WebServiceManager
Creating a Todo item
Listing Todo items
Lenses
States
Store
Actions
Views
ViewControllers
MasterViewController
IBActions
TableView delegates and DataSource
DetailsViewController
Summary
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 very 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 Web, macOS, tvOS, and watchOS. Through this book, you'll learn to develop extendable, smart, and maintainable code using functional programming techniques.
Chapter 1, Getting Started with Functional Programming in Swift, introduces functional programming paradigms by attempting to answer the questions of Why functional programming matters? and What is functional programming? It covers topics such as immutability, stateless programming, pure, first-class, and higher-order functions. Also, this chapter will introduce the Swift programming language basics as they are essential for the rest of the book.
Chapter 2, Functions and Closures, begins with the definition of functions, continues with other related topics, such as function types, and finally concludes with more advanced topics such as first-class functions, higher-order functions, function composition, custom operator definition, closures, function currying, recursion, and memoization.
Chapter 3, Types and Type Casting, takes a look at types in general by introducing different kinds of types such as concrete, abstract, product, and sum. 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. Finally, we will explore 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 being introduced to 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. We will explore type erasure by an example and finally we will learn how to extend generic types and how to subclass generic classes.
Chapter 6, Map, Filter, and Reduce, introduces the concept of higher-kinded types, Functor, Applicative Functor, and Monad. This chapter covers higher-order functions/methods such as map, flatMap, filter, and reduce in the Swift programming language with examples. The chapter continues by providing implementation of map, filter, flatMap, and flatten in terms of reduce. Then it provides, apply, join, chaining higher-order functions, and zip. Finally, it provides practical examples of higher-order function usage.
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. Finally, this chapter will cover the error handling with an example.
Chapter 8, Functional Data Structures, introduces the concept of functional data structures and explores examples of data structures implemented in a 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 consider cases for mutability and go through an example to compare mutability and immutability effects on our code. Finally, we will explore copy constructors and lenses.
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 with Vapor framework and an iOS application, employing the concepts covered in previous chapters. 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.
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 8.3 or newer with Swift 3.1 or newer.
This book is for iOS, Web, and macOS developers with basic knowledge of Swift programming who are interested in functional programming techniques. Prior knowledge of object-oriented programming and iOS app development familiarity is assumed.
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.
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.
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 Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Swift-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!
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 https://www.packtpub.com/sites/default/files/downloads/SwiftFunctionalProgramming_ColorImages.pdf.
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 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.
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.
Getting onto the functional programming bandwagon needs a mindset shift, and changing our mindset is not an easy task as it takes a considerable amount of time to master a paradigm such as object-oriented programming. It needs a thorough approach, but it should also be easy to grasp. That is why we will be introduced to functional programming paradigms first, before going through each topic in detail.
This chapter introduces immutability, pattern matching, closures, as well as pure, first-class, and higher-order functions with Swift. Although all the topics in this chapter will be covered in detail in upcoming chapters, it is going to be helpful to have a broad view of the paradigms. In addition, this chapter will introduce Swift, as it is important to know the basics of the language to utilize in functional programming.
The following topics will be covered, along with examples:
Why functional programming matters
What is FP?
Swift language basics
Immutability
First-class, higher-order, and pure functions
Optionals and pattern matching
Closures
Type aliasing
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 into 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 the software without being concerned about the other parts.
Dividing software into smaller pieces is not the biggest challenge in most 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 of 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, and 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 of different objects remains difficult because, in OOP, objects are open to change and mutation.
In Functional Programming (FP), 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; in other words, they do not have side effects. 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 FP 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 limit of the speed 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 to be no end to how many processors we will have in our computers. A larger number of processors to be used for a program means a more complex multithreading and multicore mechanism to handle it. FP eliminates the need for a complex multicore programming mechanism as pure functions are not dependent on any instances or data outside of themselves. It is easy to change pure functions without changing other parts of the software.
FP embraces immutability and stateless programming, and makes applications easy to maintain and extend, as managing states and tracking mutation in code is not a trivial task. In fact, Facebook, in the documentation of immutable.js, a framework that brings immutable data structures to JavaScript, states that "Much of what makes application development difficult is tracking mutation and maintaining state."
FP is a declarative programming style, so functionally written code declares the operations, expressions, and what needs to be done. Declarations are easy to trace and less verbose as, opposed to imperative programming, which sends orders to the compiler, it is verbose and hard to trace. Embracing immutability and being declarative makes applications easier to maintain and extend. We will look into examples of declarative versus imperative programming later in this chapter.
Swift is an open-source programming language developed by Apple that combines OOP and protocol-oriented programming (POP) with FP paradigms. Swift is not a pure FP language such as Haskell, Clojure, or F#, but it provides tools that facilitate FP. Swift can be used along with Objective-C to develop macOS, iOS, tvOS, and watchOS applications. Swift can also be used on Ubuntu Linux to develop web applications. This book explains Swift 3.1 and utilizes Xcode 8.3.2 compatible source code at a GitHub (https://github.com/PacktPublishing/Swift-Functional-Programming) repository, which will be updated frequently to catch up with changes to Swift.
Swift has borrowed many concepts from other programming languages, such as Scala, Haskell, C#, Rust, and Objective-C, and has the following features.
Swift makes it easy to define immutable values--in other words, constants--and empowers FP, as immutability is one of the key concepts in FP. Once constants are initialized, they cannot be altered or mutated. Although it is possible to achieve immutability in languages such as Java, it is not as easy as Swift. To define any immutable type in Swift, the let keyword can be used no matter if it is a custom type, collection type, or a Struct/enum type.
Swift provides very powerful structures and enumerations that are passed by values and can be stateless, and, therefore, very efficient. Stateless programming simplifies the concurrency and multithreading, as pointed out in previous sections of this chapter.
Functions are first-class types in Swift, just as in languages such as Ruby, JavaScript, and Go, and can be stored, passed, and returned. First-class functions empower the FP style in Swift.
Higher-order functions can receive other functions as their parameters. Swift provides higher-order functions such as map, filter, and reduce. Also, in Swift, we can develop our own higher-order functions and DSLs.
Closures are blocks of codes that can be passed around. Closures capture the constants and variables of the context in which they are defined. Swift provides closures with a simpler syntax than Objective-C blocks.
Swift provides subscripts that are shortcuts to access members of collections, lists, sequences, or custom types. Subscripts can be used to set and get values by an index without needing separate methods for the setting and getting.
Pattern matching is the ability to de-structure values and match different switch cases based on correct value matches. Pattern matching capabilities exist in languages such as Scala, Erlang, and Haskell. Swift provides powerful switch cases and if cases with where clauses as well.
Swift provides generics that make it possible to write code that is not specific to a type and can be utilized for different types.
Swift provides optional types that can have some or none values. Swift also provides optional chaining to use optionals safely and efficiently. Optional chaining empowers us to query and call properties, methods, and subscripts on optional types that may be nil.
Swift provides extensions that are similar to categories in Objective-C. Extensions add new functionality to an existing class, structure, enumeration, or protocol type, even if it is closed-source.
Bridging headers empower us to mix Swift with Objective-C in our projects. This functionality makes it possible to use our previously written Objective-C code in Swift projects and vice versa.
Swift handles memory management through Automatic Reference Counting (ARC), like Objective-C and unlike languages such as Java and C#, which utilize garbage collection. ARC is used to initialize and de-initialize the resources, thereby releasing memory allocations of the class instances when they are no longer required. ARC tracks, retains, and releases in the code instances to manage the memory resources effectively.
Xcode provides the Read Eval Print Loop (REPL) command-line environment to experiment with the Swift programming language without the need to write a program. Also, Swift provides Playgrounds, which enable us to test Swift code snippets quickly and see the results in real time via a visual interface. Source codes for the first ten chapters of this book are provided as Playgrounds in the GitHub repo and Packt Publishing website.
This section will provide a brief introduction to the basics of the Swift programming language. Topics in the upcoming subsections of this chapter will be explained in detail in later chapters.
