Swift 3.0 中的 UIView?() 构造函数发生了什么变化?

What happened to the UIView?() constructor in Swift 3.0?

在Swift 2.2中,我经常使用类似于let x = UIView?()的简洁语法来声明变量。这给了 x UIView? 类型,并用 nil 初始化了它。 (当然,在这些示例中,您可以使用任何类型而不是 UIView

但是,当我在 Swift 3.0 中执行相同操作时,出现错误: Cannot invoke initializer for type 'UIView?' with no arguments。它还说 Overloads for 'UIView?' exist with these partially matching parameter lists: (Wrapped), (nilLiteral: ())。不知何故,我不认为 UIView?(nilLiteral: ()) 是我所追求的。

当然,还有其他替代方法可以做同样的事情,例如 let x: UIView? = nillet x = nil as UIView(),但它们比我以前使用的方法更冗长。 UIView?() 构造函数是在 Swift 3.0 中删除的,还是以我尚未发现的形式被替换的?

下面确实将 x 初始化为 nil,括号完全是多余的。

var x: UIView?
return x == nil

会 return 是吗

查看开发者文档了解更多信息。

https://developer.apple.com/library/content//documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

If you define an optional variable without providing a default value, the variable is automatically set to nil for you:

var surveyAnswer: String?
// surveyAnswer is automatically set to nil

@Hamish 发表评论澄清 UIView?() 不再有效的原因:

》UIView的语法?只是 Optional 的语法糖,因此 UIView?() 只是 Optional.init() 的语法糖。在Swift2中,Optional的init()构造了一个新的可选值设置为.None。所以是的,它工作正常。然而,在 Swift 3 中,这个初始化程序已被删除,这就是为什么 UIView?() 不再有效”