Swift 3.0 中的 UIView?() 构造函数发生了什么变化? [英] What happened to the UIView?() constructor in Swift 3.0?

查看:28
本文介绍了Swift 3.0 中的 UIView?() 构造函数发生了什么变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Swift 2.2, I often declared variables using a concise syntax similar to let x = UIView?(). This gave x the UIView? type, and initialised it with nil. (Of course, you could use any type instead of UIView in these examples)

但是,当我在 Swift 3.0 中执行相同操作时,出现错误:无法为UIView"类型调用初始化程序?没有参数.它还说 Overloads for 'UIView?'存在这些部分匹配的参数列表:(Wrapped), (nilLiteral: ()).不知何故,我不认为 UIView?(nilLiteral: ()) 是我所追求的.

However, when I do the same in Swift 3.0, I get an error: Cannot invoke initializer for type 'UIView?' with no arguments. It also says that Overloads for 'UIView?' exist with these partially matching parameter lists: (Wrapped), (nilLiteral: ()). Somehow, I don't think UIView?(nilLiteral: ()) is quite what I'm after.

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

Naturally, there are other alternative methods to do the same thing, such as let x: UIView? = nil and let x = nil as UIView(), but they're more verbose than the method I was using previously. Was the UIView?() constructor removed in Swift 3.0, or has it been replaced in a form that I've not yet discovered?

推荐答案

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

The following does initialise x to nil, the brackets are entirely superfluous.

var x: UIView?
return x == nil

会返回真

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

Check out the developer docs for more information.

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?() 不再有效的原因:

@Hamish posted a comment to clarify the reason why UIView?() no longer works:

UIView 的语法?只是 Optional 的语法糖,因此 UIView?() 只是 Optional.init() 的语法糖.在 Swift 2 中,Optional 的 init() 构造了一个新的可选值,设置为 .None.所以是的,它工作正常.然而,在 Swift 3 中,这个初始化器已被删除,这就是 UIView?() 不再起作用的原因"

这篇关于Swift 3.0 中的 UIView?() 构造函数发生了什么变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆