Reader small image

You're reading from  Learning Swift Second Edition - Second Edition

Product typeBook
Published inMar 2016
Reading LevelBeginner
Publisher
ISBN-139781785887512
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Andrew J Wagner
Andrew J Wagner
author image
Andrew J Wagner

Contacted on 5 Aug 16 Andrew J Wagner is a software developer who concentrates on iOS development and backend web services. He has a degree in computer engineering from Rensselaer Polytechnic Institute, New York. Currently, he works for a development shop based in Denver, CO named Chronos Interactive. He has experience working with and for large-scale companies and small-scale companies as well as running his own contracting and app companies. He is passionate about using computers as a creative outlet and writing software that is beautiful in implementation, functionality, and experience. When he isn't working or spending time with friends and family, he writes for his blog at http://drewag.me. I would like to thank my friends and family for being there for me as support for both my troubles and triumphs. Without their encouragement, I would not have finished this book or achieved any of the other things in my life that make me proud. An especially big thanks to my parents, Fern and Joe, for continually providing me the the tools I need to do the things I love.
Read more about Andrew J Wagner

Right arrow

Chapter 5. A Modern Paradigm – Closures and Functional Programming

So far, we have been programming using the paradigm called object-oriented programming, where everything in a program is represented as an object that can be manipulated and passed around to other objects. This is the most popular way to create apps because it is a very intuitive way to think about software and it goes well with the way Apple has designed their frameworks. However, there are some drawbacks to this technique. The biggest one is that the state of data can be very hard to track and reason about. If we have a thousand different objects floating around in our app, all with different information, it can be hard to track down where the bugs occurred and it can be hard to understand how the whole system fits together. Another paradigm of programming that can help with this problem is called functional programming.

Some programming languages are designed to use only functional programming, but Swift is designed primarily...

Functional programming philosophy


Before we jump into writing code, let's discuss the ideas and motivations behind functional programming.

State and side effects

Functional programming makes it significantly easier to think of each component in isolation. This includes things such as types, functions, and methods. If we can wrap our minds around everything that is input into these code components and everything that should be returned from them, we could analyze the code easily to ensure that there are no bugs and it performs well. Every type is created with a certain number of parameters and each method and function in a program has a certain number of parameters and return values. Normally, we think about these as the only inputs and outputs, but the reality is that often there are more. We refer to these extra inputs and outputs as state.

In a more general sense, state is any stored information, however temporary, that can be changed. Let's consider a simple double function:

func double(input...

Closures


In Swift, functions are considered first-class citizens, which means that they can be treated the same as any other type. They can be assigned to variables and be passed in and out of other functions. When treated this way, we call them closures. This is an extremely critical piece to write more declarative code because it allows us to treat functionalities like objects. Instead of thinking of functions as a collection of code to be executed, we can start to think about them more like a recipe to get something done. Just like you can give just about any recipe to a chef to cook, you can create types and methods that take a closure to perform some customizable behavior.

Closures as variables

Let's take a look at how closures work in Swift. The simplest way to capture a closure in a variable is to define the function and then use its name to assign it to a variable:

func double(input: Int) -> Int {
        return input * 2
}

var doubleClosure = double
print(doubleClosure(2)) // 4...

Building blocks of functional programming in Swift


The first thing to realize is that Swift is not a functional programming language. At its core, it will always be an object-oriented programming language. However, since functions in Swift are first-class citizens, we can use some of the core techniques. Swift provides some built-in methods to get us started.

Filter

The first method we are going to discuss is called filter. As the name suggests, this method is used to filter elements in a list. For example, we can filter our numbers array to include only even numbers:

var evenNumbers = numbers.filter({ element in
    element % 2 == 0
}) // [2, 4]

The closure we provide to filter will be called once for each element in the array. It is tasked with returning true if the element needs to be included in the result and false otherwise. The preceding closure takes advantage of the implied return value and simply returns true if the number has a remainder of zero when being divided by two.

Note that...

Lazy evaluation


A powerful feature of Swift is the ability to make these operations lazily evaluated. This means that, just like a lazy person would do, a value is only calculated when it is absolutely necessary and at the latest point possible.

First, it is important to realize the order in which these methods are executed. For example, what if we only want the first element of our numbers to be mapped to strings:

var firstString = numbers.map({String($0)}).first

This works well, except that we actually converted every number to a string to get to just the first one. That is because each step of the chain is completed in its entirety before the next one can be executed. To prevent this, Swift has a built-in method called lazy.

Lazy creates a new version of a container that only pulls specific values from it when it is specifically requested. This means that lazy essentially allows each element to flow through a series of functions one at a time, as it is needed. You can think about it like...

Example


Let's take a look at what this looks like in practice. We can use some of the techniques we learned in this chapter to write a different and possibly better implementation of our party inviter.

We can start by defining the same input data:

//: List of people to invite
let invitees = [
    "Sarah",
    "Jamison",
    "Marcos",
    "Roana",
    "Neena",
]

//: Dictionary of shows organized by genre
var showsByGenre = [
    "Comedy": "Modern Family",
    "Drama": "Breaking Bad",
    "Variety": "The Colbert Report",
]

In this implementation, we are making the invitees list, which is just a constant list of names and the shows by genre dictionary variable. This is because we are going to be mapping our invitees list to a list of invitation text. As we do the mapping, we will have to pick a random genre to assign to the current invitee, and in order to avoid assigning the same genre more than once, we can remove the genre from the dictionary.

So let's write the random genre function:

func pickAndRemoveRandomGenre...

Summary


In this chapter, we have had to shift the way we think about code. At the very least, this is a great exercise so we don't get set in our programming ways. We have covered the philosophy behind functional programming and how it differs from object-oriented programming. We have looked into the specifics of closures and how they enable functional programming techniques in Swift. Lastly, we explored some of the specific functional methods that Swift has built in.

The sign of a truly great programmer is not someone who knows a lot about one tool, but one who knows which tool to use when. We get there by learning and practicing using lots of different tools and techniques without ever becoming too attached to a specific one.

Once you are comfortable with the concepts of closures and functional programming, you are ready to move on to our next topic, generics. Generics is our first opportunity to make the strongly typed nature of Swift really work for us.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning Swift Second Edition - Second Edition
Published in: Mar 2016Publisher: ISBN-13: 9781785887512
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Andrew J Wagner

Contacted on 5 Aug 16 Andrew J Wagner is a software developer who concentrates on iOS development and backend web services. He has a degree in computer engineering from Rensselaer Polytechnic Institute, New York. Currently, he works for a development shop based in Denver, CO named Chronos Interactive. He has experience working with and for large-scale companies and small-scale companies as well as running his own contracting and app companies. He is passionate about using computers as a creative outlet and writing software that is beautiful in implementation, functionality, and experience. When he isn't working or spending time with friends and family, he writes for his blog at http://drewag.me. I would like to thank my friends and family for being there for me as support for both my troubles and triumphs. Without their encouragement, I would not have finished this book or achieved any of the other things in my life that make me proud. An especially big thanks to my parents, Fern and Joe, for continually providing me the the tools I need to do the things I love.
Read more about Andrew J Wagner