将示例代码添加到类型的示例代码让我感到困惑 [英] Confused by the example code which adds new instance methods to types

查看:96
本文介绍了将示例代码添加到类型的示例代码让我感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码片段是从官方文档,它用于演示如何使用扩展将方法添加到现有类型。

 扩展名Int {
func repetitions(task:() - > Void){
for _ in 0 ..< self {
task()//这里发生了什么?



$ b 3.repetitions {//为什么我不必称为重复()`
print(您好!)
}

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



非常感谢

解决方案

重复是一个函数,接受一个函数作为参数,并多次调用该函数。



为了调用 repeat ,我们可以(注意,这是Swift 3):

  func sayHi(){
print(Hello)

3.repetitions(任务:sayHi)

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

$ p $ 3.repetitions(任务:{print(Hello})

但是在这种情况下,我们可以在此调用中省略括号< repetitions $ b

  3.repetitions {print(Hello)} {$ c>}并使用 trailing 语法:



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

这篇关于将示例代码添加到类型的示例代码让我感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆