使用闭包参数分配闭包

meo*_*eow 4 closures swift

假设我有这门课

class ClosureTest{
    var nestedClosure: (((String) -> Void) -> Void)?
}
Run Code Online (Sandbox Code Playgroud)

如何给 赋值nestedClosure

我尝试了下面的代码,但出现错误。有人可以帮忙解释一下吗?

let cTest = ClosureTest()
cTest.nestedClosure = {{ myStr -> Void in } -> Void }
Run Code Online (Sandbox Code Playgroud)

And*_*jen 5

首先,类型别名将有助于减少代码中的所有括号:

typealias InnerClosure = ((String) -> Void)

class ClosureTest{
    var nestedClosure: ((InnerClosure) -> Void)?
}

Run Code Online (Sandbox Code Playgroud)

当你想给 赋值时nestedClosure,你需要提供一个闭包,它接受一个InnerClosure参数并且不返回任何内容,因此:

let cTest = ClosureTest()
cTest.nestedClosure = { (arg:InnerClosure) in
    print ("calling arg from nestedClosure:")
    arg("called from outer space") // call the inner closure
}
Run Code Online (Sandbox Code Playgroud)

要使用nestedClosure,您需要提供type 的具体InnerClosure

let innerClosureValue:InnerClosure = { txt in
    print ("the inner closure; txt: \(txt)")
}

cTest.nestedClosure?(innerClosureValue)
Run Code Online (Sandbox Code Playgroud)

那么输出是:

从nestedClosure调用arg:
内部闭包;txt:从外太空呼叫

或者,没有innerClosureValue变量:

cTest.nestedClosure?({ txt in
    print ("Or this: \(txt)")
})
Run Code Online (Sandbox Code Playgroud)