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

不羁岁月 提交于 2019-12-12 04:22:26

问题


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


回答1:


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



回答2:


Why use task() inside function body?

The task parameter is defined as a closure aka an anonymous function:

task: () -> Void

This says that the function expects another function as a parameter, one which takes no arguments and returns no values.

Calling task() invokes that function which is passed in.

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

Search for "Trailing Closure Syntax". If the last argument to a Swift function is a closure, you can attach it to the call outside of the () argument list. Or in other words, this is exactly the same:

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

(whether you have to use task: as the keyword argument depends on whether you use Swift 2 or 3.



来源:https://stackoverflow.com/questions/38505094/confused-by-the-example-code-which-adds-new-instance-methods-to-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!