user7341005
user7341005

Reputation: 285

how to understand "add new instance methods by extentions" from apple's guidebook?

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

}

Upvotes: 2

Views: 28

Answers (1)

vacawama
vacawama

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

Related Questions