Reputation: 28
// first segment
func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, condition: lessThanTen)
// second segment
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42, 597, 12)
What's the difference between list
in segment 1 and numbers
in segment 2? Why one is [Int]
another is Int...
?
I try to exchange them in playground, error was shown.
Upvotes: 0
Views: 757
Reputation: 622
This indicates the parameter is a array type.
This indicates the parameter is a variadic parameter. A variadic parameter accepts zero or more values of a specified type.
A variadic parameter is used as a constant array within function body, the difference happens in calling function, we can call function with variadic parameter in none parameter style, like function_variadic_type(), and function with array type can't do this, there must be a array passed into function, like function_array_type([1, 2]).
Upvotes: 1
Reputation: 933
It has no difference. Your code is fine. You just have to delete 'condition' in line 17. The code should be like this
func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, lessThanTen)
// second segment
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42, 597, 12)
Upvotes: 0