Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

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

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)

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

var x: UIView?
return x == nil

Will return 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 posted a comment to clarify the reason why UIView?() no longer works:

“The syntax UIView? is just syntactic sugar for Optional, therefore UIView?() is just syntactic sugar for Optional.init(). In Swift 2, Optional's init() constructs a new optional value set to .None. So yes, it was working correctly. In Swift 3 however, this initialiser has been removed, which is why UIView?() no longer works”


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...