Reputation: 614
I am following Apple's eBook titled "The Swift Programming Language". In it, there is a code sample that creates a function. This function uses "-> Bool" at the end, which I understand means the function will have a boolean output.
To configure the function, it uses two input variables. One of those variables is an "Int -> Bool" (see code below). Maybe there is a better explanation of this later in the eBook but my searches could not quite explain how and why I would use the "->" nomenclature on a variable.
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, 10, 12]
hasAnyMatches(numbers, lessThanTen)
Since this is not really explained, the best way I can read the code sample is that the "condition" variable is not really a variable but a function in and of itself. Therefore the way I read the code is as follows:
"condition is a function that accepts an integer and returns a boolean variable."
Is this assumption correct?
Thank you.
Upvotes: 1
Views: 66
Reputation: 678
You assumption is correct. In Swift, functions can be passed as arguments within functions.
From what I believe, the code you are referencing is from Apple's "The Swift Programming Language" eBook. Nearby, it states that:
“A function can take another function as one of its arguments.”
Basically, what is happening here is that you have created a function, "lessThanTen()" that takes an Int argument and returns a Bool value. Next you create another function, "hasAnyMatches" that uses a function within itself (i.e, the Int -> Bool). This can be useful if you have different functions that take and return the same value types, but which have a different purpose.
You then can pass the original function as an argument just as you would a variable. The function can take any form as long as it satisfies the conditions specified the second function (i.e, the "condition: Int -> Bool").
In conclusion, in the second function you have the line
if condition(item) {
Basically, this line runs the function "condition" which, in reality, is simply another function passed as an argument. I could create any function that takes an Int and returns a Bool value and then pass it along to "hasAnyMatches".
If you want to read more about this, I would suggest looking further along in "The Swift Programming Language" to the chapter titled "Functions". There it states:
“You can use a function type such as (Int, Int) -> Int as a parameter type for another function. This enables you to leave some aspects of a function’s implementation for the function’s caller to provide when the function is called.” (Pg. 141)
I hope this answers your question :)
Upvotes: 4