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

查看:80
本文介绍了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中执行相同操作时,出现错误: Cannot invoke initializer for type 'UIView?' with no arguments.它还说Overloads for 'UIView?' exist with these partially matching parameter lists: (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(),但是它们比我以前使用的方法更为冗长.在Swift 3.0中删除了UIView?()构造函数,还是以我尚未发现的形式替换了它?

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

将返回true

查看开发者文档以获取更多信息.

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天全站免登陆