Making Things Happen: Functions - Learning Swift Programming (2015)

Learning Swift Programming (2015)

3. Making Things Happen: Functions

This chapter discusses functions. You will find that Swift functions are based on the best implementations functions in other languages. Swift functions provide you with lots of flexibility to create parameters that are both “internal” and “external,” which jives well with Objective-C. Internal and external parameters allow you to have functions that are easy to read. You’ll be able to quickly read the name of a function and know exactly what it does. This is one excellent feature of Objective-C that has made its way into Swift.

A function itself can also be passed as a parameter of another function, also known as anonymous functions. This makes it easy to pass parameters around to different contexts. Functions can contain other functions; these are called closures and are discussed in Chapter 6, “Reusable Code: Closures.” Closures and functions go hand in hand.

A function groups commonly used code together so that it can be reused as many times as is needed. Say that you have a game in which a character jumps in the air, which is a super common functionality in a game. You would need to write the code to make the character jump. Jumping in games gets rather complicated, and you wouldn’t want to rewrite that code every time you wanted the character to jump; handling the jumping character that way would be messy and error prone. Instead, you could create a function to wrap all that jumping code into a nice little package of goodness. Then, instead of writing all that code again, you could just use your jump() function. This is like using a real-life button press to make something work. That button connects to all the functionality contained within the component you’re activating. You don’t necessarily have to know how it works; you just know that pressing the button will make it work.

When you think about writing Swift code, you have to realize that there is a lot of functionality that just works. You may never know how it was written or how many lines of code it took to write it. You just know that when you call it, it will work.

For example, calling countElements on the string "Hi" returns 2, which is the number of characters in the string. You didn’t have to write that function. It came with Swift. With Swift, you can write your own functions and then forget how you made them work. Once you’ve written jump(), you can call it to have your character jump.

Defining Functions

In Swift, a function is made up of three components: a name, parameters, and a return type. The syntax for this type of declaration is as follows:

func functionName(parameterName: parameterType) -> returnType {
//code
}

This syntax is very different from Objective-C method declarations. However, if you have ever used JavaScript, Python, C, or many other languages, then this syntax will be pretty familiar. You will find that while the structure of functions is different, there are parts that make it compatible with Objective-C.

Let’s look at some examples, starting with a function that takes no arguments and has no return values:

func sayHello() {
println("Hello!")
}

Here you write the keyword func and then name the function sayHello. You use () to house parameters, when you need them; for now you can leave these parentheses empty. You use curly brackets to contain the code that needs to run when the function is called. To call this function, you simply use its name followed by parentheses. You would call sayHello like this:

sayHello()

This is about as basic a function as you can create. You can go a step further and add an argument that allows the function to “say hello” to a specific person. To do that, you need to allow the function to take a single argument of type String that represents a name. That type of declaration might look like this:

func sayHello(name: String) {
println("Hello, \(name)!")
}

Now you’ve added a parameter to the function. That parameter is of type String and called name.


Note

If you’re following along in your own playground, it isn’t necessary to overwrite your old implementation of sayHello. The type inference in Swift allows you to differentiate between your different declarations of sayHello based on the arguments. This means that if you call this, Swift will infer that you are looking for sayHello with no arguments:

sayHello()
// Hello!

If, however, you add an argument of type String to the function call, like this, Swift will now infer that you’re looking for the implementation of sayHello that takes one argument of type String:

sayHello("Skip")
// Hello, Skip!

As long as the argument types, the return types, or both are different, declaring functions with the same name will not cause issues with the compiler. You can actually have multiple functions with the same name sitting in the same file, so you shouldn’t erase your other functions.


Next, you’ll create another implementation of your sayHello function that says “hello” to someone a certain number of times. This will give you a chance to look at how to declare a function with multiple parameters:

func sayHello(name: String, numberOfTimes: Int) {
for _ in 1...numberOfTimes {
sayHello(name)
}
}

This function declaration can be read as “a function named sayHello that takes two arguments of type String and type Int with no return value.” The syntax is almost identical to that of the single argument function, just with an extra comma added to separate the arguments. You are even using the same name for the function. In fact, you are calling the first implementation of sayHello within the new declaration. Now, if you wanted to use this function, here’s how it would look:

sayHello("Skip", 5)
//Hello Skip!
//Hello Skip!
//Hello Skip!
//Hello Skip!
//Hello Skip!

We’ll elaborate a bit more on how Swift differentiates between these declarations when we discuss function types later in the chapter in “Functions as Types,” but for now, we’re going to move on to adding a return type to the function implementations.

To add a return argument in the function declaration, you simply include the pointer arrow, ->, followed by the return type.

Return Types

Next you’ll create a function that returns its sum, which will also be of return type Int:

func sum(a: Int, b: Int) -> Int {
return a + b
}

This declaration can be read as “a function, sum, that takes two arguments of type Int and has a return value of type Int.” If you wanted to call the new function, it could look something like this:

let total = sum(14, 52)
// total = 66

Returning a single value is just fine, but sometimes you want to return multiple values. In Objective-C, this problem is usually solved by creating an object class or by returning some sort of collection. These solutions would work in Swift as well, but there is a better way: You can return multiple arguments in Swift by using tuples, as described in the next section.

Multiple Return Values

Like Objective-C functions, Swift functions can return only one value. Unlike Objective-C, though, Swift lets you use tuples as values, which can be useful for packaging together multiple return values so that you can pass around multiple values as one value. Consider a situation where a function is required to return the sum of two numbers as well as the higher of the two. This means that you need the function to returns two values, both of type Intencapsulated in a tuple. Here’s what it looks like:

func sumAndCeiling(a: Int, b: Int) -> (Int, Int) {
let ceiling = a > b ? a : b
let sum = a + b
return (sum, ceiling)
}

You can declare multiple return values by encapsulating them in parentheses, separated by a comma. This is the syntax for a tuple. The preceding function can be read “a function named sumAndCeiling that takes two arguments of type Int and returns a tuple of type (Int, Int).” You can grab values from the returned tuple, from its indexes, like so:

let result = sumAndCeiling(4, 52)
let sum = result.0
let ceiling = result.1

This is a good way to return multiple values within one function, but using indexes to access values can be confusing. It’s also not very pretty, and it’s hard to remember which is which. Imagine if someone decided to change the order of the tuples without reading how they were used. It wouldn’t be very smart or very nice, and it would severely mess things up. It’s more helpful to name the values within a tuple.

Here’s how you can modify the sumAndCeiling function with named values within the tuple:

func sumAndCeiling(a: Int, b: Int) -> (sum: Int, ceiling: Int) {
let ceiling = a > b ? a : b
let sum = a + b
return (sum, ceiling)
}

The syntax for a named tuple is almost identical to the syntax of a parameter. Adding named tuples is an easy way to create more readable code while dealing with fewer errors. Here’s a new implementation:

let result = sumAndCeiling(16, 103)
let sum = result.sum
// sum = 119
// result.sum == result.0
let ceiling = result.ceiling
// ceiling = 103
// result.ceiling == result.1


Note

In general, I prefer accessing tuples by name rather than by index because it is easier to read. This way you always know exactly what the function is returning.


More on Parameters

You already know how to use parameters in functions. As discussed in the following sections, Swift also provides the following:

■ External parameter names

■ Default parameter values

■ Variadic parameters

■ In-out parameters

■ Functions as parameters

External Parameter Names

Usually you create a function with parameters and just pass them. However, external parameters must be written. Part of what makes Objective-C such a powerful language is its descriptiveness. Swift engineers wanted to also include that descriptiveness, and this is why the language includes external parameter names. External parameters allow for extra clarity. The syntax for including external parameter names in a function looks like this:

func someFunction(externalName internalName: parameterType) -> returnType {
// Code goes here
}

The keyword func is followed by the name of the function. In the parameters of the function, there’s an extra name for the parameters. The whole parameter is an external name followed by an internal parameter followed by the parameter type. The return type of the function follows the function parameters, as usual.

Here’s a function that takes the names of two people and introduces them to each other:

func introduce(nameOfPersonOne nameOne: String, nameOfPersonTwo nameTwo: String) {
println("Hi \(nameOne), I'd like you to meet \(nameTwo).")
}

Writing this function with external parameters makes it more readable. If someone saw a function called introduce, it might not provide enough detail for the person to implement it. With a function called introduce(nameOfPersonOne:,nameOfPersonTwo:), you know for sure that you have a function that introduces two people to each other. You know that you are introducing person one to person two. By adding two external parameters to the function declaration, when you call the introduce function, the nameOfPersonOne and nameOfPersonTwo parameters will appear in the call itself. This is what it looks like:

introduce(nameOfPersonOne: "John", nameOfPersonTwo: "Joe")
// Hi John, I'd like you to meet Joe.

By including external parameters in functions, you remove the ambiguity from arguments, which helps a lot when sharing code.

You might want your external parameters and internal parameters to have the same name. It seems silly to repeat yourself, and Swift thought it was silly, too. By adding the pound sign (#) as a prefix to an internal parameter name, you are saying that you want to include an external parameter using the same name as the internal one. You could redeclare the introduce function with shared parameter names, like so:

func introduce(#nameOne: String, #nameTwo: String) {
println("Hi \(nameOne), I'd like you to meet \(nameTwo).")
}

This syntax makes it easy to include external parameters in functions without rewriting the internal parameters. If you wanted to call the introduce function, it would look like this:

introduce(nameOne: "Sara", nameTwo: "Jane")
// Hi Sara, I'd like you to meet Jane.

These external parameters aren’t required, but they do make for much greater readability.

Default Parameter Values

Swift supports default parameters unlike in Objective-C where there is no concept of default parameter values. The following is an example of a function that adds punctuation to a sentence, where you declare a period to be the default punctuation:

func addPunctuation(#sentence: String, punctuation: String = ".") -> String {
return sentence + punctuation
}

If a parameter is declared with a default value, it will be made into an external parameter. If you’d like to override this functionality and not include an external parameter, you can insert an underscore (_) as your external variable. If you wanted a version of addPunctuation that had no external parameters, its declaration would look like this:

func addPunctuation(sentence: String, _ punctuation: String = ".") -> String {
return sentence + punctuation
}

Now you can remove the underscore from the parameters. Then you can call the function with or without the punctuation parameter, like this:

let completeSentence = addPunctuation(sentence: "Hello World")
// completeSentence = Hello World.

You don’t declare any value for punctuation. The default parameter will be used, and you can omit any mention of it in the function call.

What if you want to use an exclamation point? Just add it in the parameters, like so:

let excitedSentence = addPunctuation(sentence: "Hello World", punctuation: "!")
// excitedSentence = Hello World!

Next you’re going to learn about another language feature that allows an unlimited number of arguments to be implemented. Let’s talk about variadic parameters.

Variadic Parameters

Variadic parameters allow you to pass as many parameters into a function as your heart desires. If you have worked in Objective-C then you know that doing this in Objective-C requires a nil terminator so that things don’t break. Swift does not require such strict rules. Swift makes it easy to implement unlimited parameters by using an ellipsis, which is three individual periods (...). You tell Swift what type you want to use, add an ellipsis, and you’re done.

The following function finds the average of a bunch of ints:

func average(numbers: Int...) -> Int {
var total = 0
for n in numbers {
total += n
}
return total / numbers.count
}

It would be nice if you could pass in any number of ints. The parameter is passed into the function as an array of ints in this case. That would be [Int]. Now you can use this array as needed. You can call the averagefunction with any number of variables:

let averageOne = average(numbers: 15, 23)
// averageOne = 19
let averageTwo = average(numbers: 13, 14, 235, 52, 6)
// averageTwo = 64
let averageThree = average(numbers: 123, 643, 8)
// averageThree = 258

One small thing to note with variadic parameters: You may already have your array of ints ready to pass to the function, but you cannot do this. You must pass multiple comma-separated parameters. If you wanted to pass an array of ints to a function, you can write the function a little differently. For example, the following function will accept one parameter of type [Int]. You can have multiple functions with the same name in Swift, so you can rewrite the function to have a second implementation that takes the array of ints:

func average(numbers: [Int]) -> Int {
var total = 0
for n in numbers {
total += n
}
return total / numbers.count
}

Now you have a function that takes an array of ints. You might have this function written exactly the same way twice in a row. That works but we are repeating ourselves. You could rewrite the first function to call the second function:

func average(numbers: Int...) -> Int {
return average(numbers)
}

Now you have a beautiful function that can take either an array of ints or an unlimited comma-separated list of ints. By using this method, you can provide multiple options to the user of whatever API you decide to make:

let arrayOfNumbers: [Int] = [3, 15, 4, 18]
let averageOfArray = average(arrayOfNumbers)
// averageOfArray = 10
let averageOfVariadic = average(3, 15, 4, 18)
// averageOfVariadic = 10

In-Out Parameters

In-out parameters allow you to pass a variable from outside the scope of a function and modify it directly inside the scope of the function. You can take a reference into the function’s scope and send it back out again—hence the keyword inout. The only syntactic difference between a normal function and a function with inout parameters is the addition of the inout keyword attached to any arguments you want to be inout. Here’s an example:

func someFunction(inout inoutParameterName: InOutParameterType) -> ReturnType {
// Your code goes here
}

Here’s a function that increments a given variable by a certain amount:

func incrementNumber(inout #number: Int, increment: Int = 1) {
number += increment
}

Now, when you call this function, you pass a reference instead of a value. You prefix the thing you want to pass in with an ampersand (&):

var totalPoints = 0
incrementNumber(number: &totalPoints)
// totalPoints = 1

In the preceding code, a totalPoints variable represents something like a player’s score. By declaring the parameter increment with a default value of 1, you make it easy to quickly increment the score by 1, and you still have the option to increase by more points when necessary. By declaring the number parameter as inout, you modify the specific reference without having to assign the result of the expression to the totalPoints variable.

Say that the user just did something worth 5 points. The function call might now look like this:

var totalPoints = 0
incrementNumber(number: &totalPoints, increment: 5)
// totalPoints = 5
incrementNumber(number: &totalPoints)
// totalPoints = 6

Functions as Types

In Swift, a function is a type. This means that it can be passed as arguments, stored in variables, and used in a variety of ways. Every function has an inherent type that is defined by its arguments and its return type. The basic syntax for expressing a function type looks like this:

(parameterTypes) -> ReturnType

This is a funky little syntax, but you can use it as you would use any other type in Swift, which makes passing around self-contained blocks of functionality easy.

Let’s next look at a basic function and then break down its type. This function is named double and takes an int named num:

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

It also returns an int. To express this function as its own type, you use the preceding syntax, like this:

(Int) -> Int

Here you add the parameter types in parentheses, and you add the return type after the arrow.

You can use this type to assign a type to a variable:

var myFunc:(Int) -> Int = double

This is similar to declaring a regular variable of type string, for example:

var myString:String = "Hey there buddy!"

You could easily make another function of the same type that has different functionality. Just as double’s functionality is to double a number, you can make a function called triple that will triple a number:

func triple(num:Int) -> Int {
return number * 3
}

The double and triple functions do different things, but their type is exactly the same. You can interchange these functions anywhere that accepts their type. Anyplace that accepts (Int) -> Int would accept both the double or triple functions. Here is a function that modifies an int based on the function you send it:

func modifyInt(#number: Int, #modifier:(Int) -> Int) -> Int {
return modifier(number)
}

While some languages just accept any old parameter, Swift is very specific about the functions it accepts as parameters.

Putting It All Together

Now it’s time to combine all the things you’ve learned so far about functions. You’ve learned that the pound sign means that the function has an external parameter named the same as its internal parameter. The parameter modifier takes a function as a type. That function must have a parameter that is an int and a return value of an int. You have two functions that meet those criteria perfectly: double and triple. If you are an Objective-C person, you are probably thinking about blocks right about now. In Objective-C, blocks allow you to pass around code similar to what you are doing here. (Hold that thought until you get to Chapter 6.) For now you can pass in the double or triple function:

let doubledValue = modifyInt(number: 15, modifier: double)
// doubledValue == 30
let tripledValue = modifyInt(number: 15, modifier: triple)
// tripledValue == 45


Note

This example is obviously completely hard coded, and your examples will be completely dynamic. For example, you would probably replace the number 30 with the current speed of the character when he hits the sonic speed button. For now, you can just settle for 30 and 45.


Listing 3.1 is an example of creating functions in Swift:

Listing 3.1 A Tiny Little Game


var map = [ [0,0,0,0,2,0,0,0,0,0],
[0,1,0,0,0,0,0,0,1,0],
[0,1,0,0,0,0,0,0,1,0],
[0,1,0,1,1,1,1,0,1,0],
[3,0,0,0,0,0,0,0,0,0]]

var currentPoint = (0,4)
func setCurrentPoint(){
for (i,row) in enumerate(map){
for (j,tile) in enumerate(row){
if tile == 3 {
currentPoint = (i,j)
return
}
}
}
}

setCurrentPoint()

func moveForward() -> Bool {
if currentPoint.1 - 1 < 0 {
println("Off Stage")
return false
}
if isWall((currentPoint.0,currentPoint.1 - 1)) {
println("Hit Wall")
return false
}
currentPoint.1 -= 1
if isWin((currentPoint.0,currentPoint.1)){
println("You Won!")
}
return true
}

func moveBack() -> Bool {
if currentPoint.1 + 1 > map.count - 1 {
println("Off Stage")
return false
}
if isWall((currentPoint.0,currentPoint.1 + 1)) {
println("Hit Wall")
return false
}
currentPoint.1 += 1
if isWin((currentPoint.0,currentPoint.1)){
println("You Won!")
}
return true
}

func moveLeft() -> Bool {
if currentPoint.0 - 1 < 0 {
return false
}
if isWall((currentPoint.0 - 1,currentPoint.1)) {
println("Hit Wall")
return false
}
currentPoint.0 -= 1
if isWin((currentPoint.0,currentPoint.1)){
println("You Won!")
}
return true
}

func moveRight() -> Bool {
if currentPoint.0 + 1 > map.count - 1 {
println("Off Stage")
return false
}
if isWall((currentPoint.0 + 1,currentPoint.1)) {
println("Hit Wall")
return false
}
currentPoint.0 += 1
if isWin((currentPoint.0,currentPoint.1)){
println("You Won!")
}
return true
}

func isWall(spot:(Int,Int)) -> Bool {
if map[spot.0][spot.1] == 1 {
return true
}
return false
}

func isWin(spot:(Int,Int)) -> Bool {
println(spot)
println(map[spot.0][spot.1])
if map[spot.0][spot.1] == 2 {
return true
}
return false
}

moveLeft()
moveLeft()
moveLeft()
moveLeft()
moveBack()
moveBack()
moveBack()
moveBack()


This is a map game. This game allows the user to navigate through the map by using function calls. The goal is to find the secret present (the number 2). If the player combines the right moves in the move function, he or she can find the secret present. Your current status will read out in the console log.

Let’s step through this code:

■ Line 1: You have a multidimensional array map, which is an array within an array.

■ The function setCurrentPoint finds the 3, which is the starting point, and sets it as the current point.

■ You have four directional functions that move the current point’s x or y position.

■ In each of those functions you check whether you hit a wall using that isWall function.

■ In each of those functions you also move the player’s actual position.

■ After the position is moved you check whether you won the game by seeing whether you landed on a 2.

■ You can call each function one by one and the console will trace out whether you won or not. It will not move if you are going to hit a wall. It will also not move if you are going to go off stage.

Summary

This chapter just scratches the surface of using functions in Swift. You learned most of what there is to learn syntactically, but there is more to come with the possibilities of implementation. Now that you know all the different ways to use functions in Swift, it is now time to start experimenting and implementing. Functions are one of the puzzle pieces of object-oriented programming, but you need more pieces to complete the picture. Next you will learn how to turn functions into methods of a class, struct, and enum. You will learn the basic building blocks of structuring code. When combined with classes, structs, and enums, functions become a part of that bigger object-oriented programming picture.