Game Development Reference
In-Depth Information
the current body of main.swift with this code and run it. You will see 600 printed to
the console.
inout Parameters
In all of the previous examples, you have never tried to change the value of a passed-in
variable while you were in the body of the function. You probably think you could just set
the parameter's value to something else and all would be fine. This is not the case. When
you pass a parameter like you have been doing so far, you are actually passing a copy of
the value to the function, and the parameter is treated as a constant.
If you need to change the value of a parameter in the body of a function, you have to pass
a reference to the variable you are passing in. This is done using a Swift inout paramet-
er. Take a look at the swapWords() function:
func swapWords( inout param1: String, inout param2: String) {
var tmp: String = param1
param1 = param2
param2 = tmp
}
var word1 = "Hello"
var word2 = "Goodbye"
swapWords(&word1, &word2)
println(word1)
println(word2)
Here you have a simple function the takes two String s and swaps their values. To use
the function, you create two String variables and pass them to swapWords() . After
the function is executed, you print the words.
Notice the two parameters with the keyword inout in front of them. This is how you tell
the Swift compiler that this function is expecting a reference to a variable and not a
copy of a variable. Now look at the invocation of this function. You have prepended an
ampersand (&) to each of the variables being passed to the function. This indicates you
are passing a reference to the variable.
When you run the program, you will see that the values have been swapped. When you
pass parameters using this method, you are said to be passing them by reference .
Search WWH ::




Custom Search