Game Development Reference
In-Depth Information
func thisFunctionDoesNothing() {
}
Variadic Parameters
You can also pass a variable number of arguments to a single parameter in a Swift func-
tion. This parameter is called a
variadic
parameter. When defining a variadic parameter,
you follow the type with three dots (
...
).
func catWords(words: String...) ->String {
var cattedWords = ""
for word in words {
cattedWords+=word
}
return cattedWords
}
This function takes a variable number of
String
values and stores them in an array
named
words
. It then iterates over the array appending each
String
to the variable
cattedWords
and then returns a single
String
representing all the words as one
String
.
To call the function, you simple invoke it, like you did before, passing it any number of
String
values
.
println(catWords("Hello", "World", "I", "Am", "Swift"))
Go ahead and run this code. You will see all the words as one. Then change the number of
String
values you pass to this function and play around with it while watching the res-
ults.
You can add other parameters to a function that has a variadic parameter, but there can be
only one variadic parameter, and it must be the last parameter in the function definition.
Tuples
Swift functions can also return multiple values called
tuples
. A function that returns a
tuple will have its return types defined in parentheses separated by commas.