Reputation: 483
It mentions that when creating for
loops we can use the shorthand of 0..3
and 0...3
to replace i = 0; i < 3; ++i
and i = 0; i <= 3; ++i
respectively.
All very nice.
Further down the document in the Functions and Closures section it says that functions can have a variable number of arguments passed via an array.
However, in the code example we see the ...
again.
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
Is this a mistake? It seems to me that a more intuitive syntax would be numbers: Int[]
.
A few examples down we see another code sample which has exactly that:
func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {
Upvotes: 26
Views: 27899
Reputation: 1226
The type of parameter in sumOf are known as 'variadic' parameter. The parameters passed are accepted just as a group of elements and is then converted into array before using it within that function.
A great example would be this post.
Passing lists from one function to another in Swift
Upvotes: 5
Reputation: 1286
In case of all arguments are Int numbers: Int[] would be intuitive. But if you have code like this:
func foo(args:AnyObject...) {
for arg: AnyObject in args {
println(arg)
}
}
foo(5, "bar", NSView())
output:
5
bar
<NSView: 0x7fc5c1f0b450>
Upvotes: 53