如何将参数传递给多个尾随闭包?

How to pass argument to multiple trailing closures?

我想在两个闭包中都打印“voala”,但出现错误:无法在范围内找到 'sound'。我在书中找到了类似的例子,但是它不起作用,所以问。

func multipleTrailing(scream sound: String, first closure1: () -> Void, second closure2: () -> Void) {
    closure1()
    closure2()
    }

multipleTrailing(scream: "voala") {
    print("\(sound), calling from closure1, omitting argument label \"first\"")
        } second: {
    print("\(sound), calling from closure2, keeping argument label \"second\"")
        }

你应该给闭包赋值。这里两个闭包都有一个 String 类型的输入参数,并且 multipleTrailing 函数将 sound 参数传递给它们。在调用方站点上,此参数可以有任何名称(这里我在两个地方都给了它们 sound),您可以访问这些值

func multipleTrailing(scream sound: String, first closure1: (String) -> Void, second closure2: (String) -> Void) {
    closure1(sound)
    closure2(sound)
}

multipleTrailing(scream: "voala") { sound in
    print("\(sound), calling from closure1, omitting argument label \"first\"")
} second: { sound in
    print("\(sound), calling from closure2, keeping argument label \"second\"")
}