2

In apple's document, when we are going to extend type:Int, we can write code like this:

enter image description here

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:

enter image description here

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){

}
user7341005
  • 285
  • 1
  • 3
  • 13
  • This is an instance of trailing closure syntax, one of the many syntactic sugars invented to make closures more convenient to work with. I give a break down of them in [this answer](http://stackoverflow.com/a/40390414/3141234). – Alexander Dec 30 '16 at 01:03

1 Answers1

3

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!")
})
vacawama
  • 150,663
  • 30
  • 266
  • 294