Ben Ben - 8 months ago 73
Swift Question

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
type, and initialised it with
. (Of course, you could use any type instead of
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
let x = nil as UIView()
, but they're more verbose than the method I was using previously. Was the
constructor removed in Swift 3.0, or has it been replaced in a form that I've not yet discovered?


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.

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”