Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Learning Swift
  • Table Of Contents Toc
  • Feedback & Rating feedback
Learning Swift

Learning Swift

By : Andrew J Wagner
4.8 (5)
close
close
Learning Swift

Learning Swift

4.8 (5)
By: Andrew J Wagner

Overview of this book

If you are looking to build iOS or OS X apps using the most modern technology, this book is ideal for you. You will find this book especially useful if you are new to programming or if you have yet to develop for iOS or OS X.
Table of Contents (13 chapters)
close
close
12
Index

Closures


In Swift, functions are considered first-class citizens, meaning that they can be treated in the same as any other type. They can be assigned to variables and passed in and out of other functions. When treated this way, we call them closures.

Closures as variables

The simplest way to capture a closure in a variable is by defining the function and then using its name to assign it to a variable:

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

var doubleClosure = double
println(doubleClosure(2)) // 4

As you can see, doubleClosure can be used just like the normal function name after it is assigned. There is actually no difference between using double and doubleClosure.

If you look at the type of doubleClosure by option-clicking on the name, you will see that the type is defined as (Int) -> Int. The basic type of any closure is (ParamterType1, ParameterType2, …) -> ReturnType.

Using this syntax, we can also define our closure inline as:

var doubleClosure2 = { (input: Double...

Unlock full access

Continue reading for free

A Packt free trial gives you instant online access to our library of over 7000 practical eBooks and videos, constantly updated with the latest in tech
bookmark search playlist font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY