如何添加@noescape注释到可选的闭包
我的function有这个签名:
func foo(bar: String, baz: ((String) -> ())? = nil)
而现在,我想要让self
在给定的封闭内逃脱。 但是当我尝试这个:
func foo(bar: String, @noescape baz: ((String) -> ())? = nil)
编译器抱怨:
@noescape may only be applied to parameters of function type
有没有可能在可选参数中使用它?
要求
如果您的要求如下:
-
baz
参数是closure
-
baz
参数用@noescape
标记(因为你想在闭包代码中省略self
) - 在调用
foo
过程中可以省略baz
参数
解
然后你可以使用下面的语法
func foo(bar: String, @noescape baz: ((String) -> ()) = { _ in } ) { }
正如你可以看到你的代码的主要区别是:
- 这里
baz
不是optional type
(但是它是一个“可选参数”) - 它的默认值是一个
empty closure
而不是一个nil
值。
例子
正如你所要求的,你现在可以通过一个封闭baz
而无需使用self
的需要
class Boo { let world = "world" func boo() { foo("hello") { (something) -> () in print(world) } } }
你也可以省略baz
参数
class Boo { let world = "world" func boo() { foo("hello") } }
更新:使用返回types与Void不同的闭包
在下面的用户评论中, TadeasKriz
询问了如何使用这种方法来处理返回值与Void
不同的闭包。
这是解决scheme
func foo(bar: String, @noescape baz: ((String) -> (Int)) = { _ in return 0 } ) { }
在这里, baz
参数需要一个types为String
参数和一个types为Int
的返回值的闭包。 正如你所看到的,我向param添加了一个默认值,一个返回0
的闭包。 请注意,将永远不会使用默认的闭包,所以你可以用你想要的任何Int
值replace0
。
现在你可以决定是否把你的封闭传给baz
参数
class Boo { let world = "world" func boo() { foo("hello") { (something) -> Int in print(world) return 100 } } }
或者,再次,你完全可以省略baz
参数。
class Boo { let world = "world" func boo() { foo("hello") } }