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 average function 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
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.