为什么 Swift 闭包变量类型不能隐式展开可选类型?
Why can't Swift closure variable types be implicitly unwrapped optionals?
例如,
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{ (x:UIAlertAction) in
...
会出现"Cannot find initializer with..."错误。
但是如果我说 UIAlertAction!
或 UIAlertAction?
而不是 UIAlertAction
,它会起作用。为什么是这样?
这些变量的类型都已经在CocoaAPI中声明了。你必须匹配它们。一个东西和一个 Optional 包装那个东西不匹配;他们是两种完全不同的类型。
另一方面,当类型已知时,您可以忽略它们。所以最简单的方法就是将 x:UIAlertAction
更改为简单的 x
甚至 _
。
例如,
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{ (x:UIAlertAction) in
...
会出现"Cannot find initializer with..."错误。
但是如果我说 UIAlertAction!
或 UIAlertAction?
而不是 UIAlertAction
,它会起作用。为什么是这样?
这些变量的类型都已经在CocoaAPI中声明了。你必须匹配它们。一个东西和一个 Optional 包装那个东西不匹配;他们是两种完全不同的类型。
另一方面,当类型已知时,您可以忽略它们。所以最简单的方法就是将 x:UIAlertAction
更改为简单的 x
甚至 _
。