Reputation: 285
In apple's document, when we are going to extend type:Int, we can write code like this:
Here is my questions:
Why can print("Hello!") work?
I mean that, in line 2: func repetitions(task: () -> Void) {, how computer can know parameter task is as same as task().
why doesn't it work if I write code like this:
here is the code, thank you:
import Foundation
func printHello(){
print("Hello!")
}
extension Int {
func repetitions(task: () -> Void) {
for _ in 0..<self {
task()
}
}
}
3.repetitions (printHello){
}
Upvotes: 2
Views: 28
Reputation: 154613
If you want to pass printHello
then you do it like this:
3.repetitions(task: printHello)
This way uses trailing closure syntax:
3.repetitions {
print("Hello!")
}
It is syntactic sugar for this:
3.repetitions(task: {
print("Hello!")
})
Upvotes: 3