Search code examples
iosswiftiboutlet

Using a typealias when declaring an IBOutlet


For teaching purposes, I'd like to be able to hide the complexity of optionals (which I will explain in the following lessons) from students on their first task. I would also, however, want them to play with the interface and connect both functions and variables.

What I'm trying to do is the following:

typealias TextField = UITextField!

Then I'm trying to do:

@IBOutlet var newShipCaptainName: TextField

This is only partially working. I can see it in the storyboard, and if I drag a UITextField and change its class to Textfield, I can connect it no problem.

However, compiling fails with the error:

Class ViewController has no initializers

Which I understand. The compiler is thinking that TextField is a non-optional variable, which can't be an IBOutlet. However, TextField is a UITextfield! so I'm not sure what I'm doing wrong.

Any ideas?


Solution

  • Apparently a type alias of an implicit unwrapped optional is treated as a non-optional so you have to explicitly add the exclamation mark:

    @IBOutlet var newShipCaptainName: TextField!