The following code snippet is copied from the official document where it is used to demonstrate how to use the Extensions to add method to existing types.
extension Int {
func repetitions(task: () -> Void) {
for _ in 0..<self {
task()//what's going on here?
}
}
}
3.repetitions { //why I don't have to call as `repetitions()`
print("Hello!")
}
Question: The question is not asking how the extinsion extens. I just feel a bit confused about this code, why it looks like so? why use task()
inside function body? Where it comes from? for the line 3.repetition
why not write it as 3.repetition()
Thanks a lot
repetitions
is a function that accepts as its parameter a function and calls that function several times.
To call repetitions
, we could say (note, this is Swift 3):
func sayHi() {
print("Hello")
}
3.repetitions(task:sayHi)
But why define an extra name sayHi
? Instead we use an anonymous function:
3.repetitions(task:{print("Hello"})
But in that case we are allowed to omit the parenthesis in this call to repetitions
and use trailing syntax:
3.repetitions{print("Hello")}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments