3

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?

olivaresF
  • 1,369
  • 2
  • 14
  • 28
  • IMO, you are going way to fast. You can't rush when teaching programming skills, especially in a language like swift. Swift looks good on the outside, but when you dig down, there is great complexity, making it unsuitable as a first language. I suggest you to teach the students how to use playgrounds first, after they learned about classes and optionals, go back to here. – Sweeper Feb 02 '17 at 06:51
  • I cannot reproduce the problem. Your code compiles without warnings or errors in my Xcode 8.2.1. – Martin R Feb 02 '17 at 06:55
  • @Sweeper thanks for your feedback! I really like playgrounds, but I do believe that I can guide them in such a way that we can build the app from the get go. – olivaresF Feb 02 '17 at 15:33
  • @MartinR what Xcode version are you using? I'm on 8.2.1 (8C1002). – olivaresF Feb 02 '17 at 15:34
  • @OlivaresF: The same version. I have copied your type alias and the outlet declaration into a new iOS project, and it compiled without problems. – Martin R Feb 02 '17 at 15:36
  • @MartinR would you mind sending me a copy of that project? fernando.olivares@me.com – olivaresF Feb 02 '17 at 15:38

1 Answers1

2

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!
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Yeah. The closest solution I've come up with is yours, which isn't great because I need to gloss over the `!`... – olivaresF Feb 02 '17 at 05:51
  • I cannot verify your claim. Try `typealias IUOInt = Int! ; let x: IUOInt = 5 ; print(type(of: x))` – Martin R Feb 02 '17 at 15:46