简体   繁体   English

如何使用这样的闭包参数初始化结构?

[英]How can you initialize a struct with a closure parameter like this?

In this question I saw today It defines a struct Effect that has a property run that is a closure that takes a Generic parameter:在我今天看到的这个问题中,它定义了一个结构Effect ,它有一个属性run ,它是一个带有通用参数的闭包:

struct Effect<T> {
    let run: (@escaping (T) -> Void) -> Void
}

Then the sample code creates an instance of Effect<Int> , and specifies the closure for the run property with something that looks like trailing closure syntax:然后示例代码创建一个Effect<Int>的实例,并使用类似于尾随闭包语法的东西指定run属性的闭包:

let anIntInTwoSeconds = Effect<Int> { callback in
    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
        callback(42)
    }
}

What makes that legal?是什么让这合法? I would expect to need to specify the run parameter explicitly in a call to the init method:我希望需要在调用 init 方法时明确指定 run 参数:

let anIntInTwoSeconds = Effect<Int>(run: { callback in
    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
        callback(42)
    }
}
)

Either version compiles and works.任何一个版本都可以编译和工作。 What in Swift makes that first version legal? Swift 中的什么使第一个版本合法? I couldn't figure out how to frame the question so that I could search for an answer.我无法弄清楚如何构建问题以便我可以搜索答案。

This works just like any function whose last parameter is a function.这就像任何 function 一样,其最后一个参数是 function。 Trailing closure syntax is trailing closure syntax.尾随闭包语法是尾随闭包语法。 The fact that the function is an initializer changes nothing. function 是初始化程序这一事实并没有改变。

So let me build up to it in stages.因此,让我分阶段进行。 You know you can say:你知道你可以说:

func myfunc(whatever: () -> ()) {}
myfunc {}

Okay, but now let's make it a static method:好的,但现在让我们将其设为 static 方法:

struct S {
    static func myfunc(whatever: () -> ()) {}
}
S.myfunc {}

OK, but init is a static method — it's just a static method whose name you are allowed to omit:好的,但是init一个 static 方法——它只是一个 static 方法,您可以省略其名称:

struct S {
    let whatever: () -> ()
}
S {} // meaning S.init {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM