Swift 可选的转义闭包参数 [英] Swift optional escaping closure parameter
问题描述
给定:
typealias Action = () -> ()
var action: Action = { }
func doStuff(stuff: String, completion: @escaping Action) {
print(stuff)
action = completion
completion()
}
func doStuffAgain() {
print("again")
action()
}
doStuff(stuff: "do stuff") {
print("swift 3!")
}
doStuffAgain()
有什么办法可以使 completion
参数(和 action
)的类型为 Action?
并保持 @escaping代码> ?
Is there any way to make the completion
parameter (and action
) of type Action?
and also keep @escaping
?
更改类型会出现以下错误:
Changing the type gives the following error:
@escaping 属性只适用于函数类型
@escaping attribute only applies to function types
删除 @escaping
属性,代码编译并运行,但似乎不正确,因为 completion
闭包正在转义函数的作用域.
Removing the @escaping
attribute, the code compiles and runs, but doesn't seem to be correct since the completion
closure is escaping the scope of the function.
推荐答案
有一个 SR-2552 报告 @escaping
无法识别函数类型别名.这就是错误 @escaping 属性仅适用于函数类型
的原因.您可以通过扩展函数签名中的函数类型来解决:
There is a SR-2552 reporting that @escaping
is not recognizing function type alias. that's why the error @escaping attribute only applies to function types
. you can workaround by expanding the function type in the function signature:
typealias Action = () -> ()
var action: Action? = { }
func doStuff(stuff: String, completion: (@escaping ()->())?) {
print(stuff)
action = completion
completion?()
}
func doStuffAgain() {
print("again")
action?()
}
doStuff(stuff: "do stuff") {
print("swift 3!")
}
doStuffAgain()
编辑 1::
我实际上使用的是 xcode 8 beta 版本,其中错误 SR-2552 是还没有解决.修复该错误,引入了一个仍然打开的新错误(您面临的错误).请参阅 SR-2444.
I was actually under a xcode 8 beta version where the bug SR-2552 was not resolved yet. fixing that bug, introduced a new one(the one you're facing) that is still open. see SR-2444.
解决方法 @Michael Ilseman 指出的临时解决方案是从可选函数类型中删除 @escaping
属性,使函数保持转义.
The workaround @Michael Ilseman pointed as a temporary solution is remove the @escaping
attribute from optional function type, that keep the function as escaping.
func doStuff(stuff: String, completion: Action?) {...}
编辑 2::
SR-2444 已关闭,明确声明参数位置中的闭包 不是 转义,需要用 @escaping
标记它们以使它们转义,但可选参数 是 隐式转义,因为 ((Int)->())?
是 Optional<(Int)->()>
的同义词,可选闭包是转义的.
The SR-2444 has been closed stating explicitly that closures in parameters positions are not escaping and need them to be marked with @escaping
to make them escaping, but the optional parameters are implicitly escaping, since ((Int)->())?
is a synonyms of Optional<(Int)->()>
, optional closures are escaping.
这篇关于Swift 可选的转义闭包参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!