对向类型添加新实例方法的示例代码感到困惑

Confused by the example code which adds new instance methods to types

以下代码片段是从 official document 复制的,用于演示如何使用扩展将方法添加到现有类型。

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!")
}

问题:问题不是问extinsion如何扩展。我只是对这段代码感到有点困惑,为什么它看起来像这样?为什么在函数体内使用 task() ?它来自哪里?对于行 3.repetition 为什么不写成 3.repetition()

非常感谢

repetitions 是一个函数,它接受一个函数作为它的参数并多次调用该函数。

要调用 repetitions,我们可以说(注意,这是 Swift 3):

func sayHi() {
    print("Hello")
}
3.repetitions(task:sayHi)

但是为什么定义一个额外的名字sayHi?相反,我们使用匿名函数:

3.repetitions(task:{print("Hello"})

但在那种情况下,我们可以在对 repetitions 的调用中省略括号并使用 trailing 语法:

3.repetitions{print("Hello")}

Why use task() inside function body?

task 参数定义为闭包,也就是匿名函数:

task: () -> Void

这表示该函数需要另一个函数作为参数,该函数不带参数且 returns 没有值。

调用 task() 调用传入的函数。

for the line 3.repetition why not write it as 3.repetition()

搜索 "Trailing Closure Syntax"。如果 Swift 函数的最后一个参数是闭包,您可以将其附加到 () 参数列表之外的调用。 或者换句话说,这完全一样:

3.repetitions(task: {
  print("Hello!")
})

(是否必须使用 task: 作为关键字参数取决于您使用的是 Swift 2 还是 3。