Search code examples
iosxcodeswiftvariboutlet

Swift - Define properties inside class


I was learning Swift and developing my test project on first XCode Beta, but few days ago I've downloaded XCode Beta4 and that's showed error in build.

My code:

class LoginModalViewController: UIViewController {

  @IBOutlet var usernameField : UITextField
  @IBOutlet var passwordField : UITextField
  @IBOutlet var loginButton : UIButton

  ...

Previously that's how I defined outlets inside controller, but in new beta it gives me an error IBOutlet property has non-optional type UITextField and suggests me to fix it in 2 ways:

  • add ! after each var
  • add ? after each var

I know that ? means optional and if I'll choose it then I need to update my code like usernameField.becomeFirstResponder() into usernameField!.becomeFirstResponder()

Adding ! solves errors perfectly..

So as I understand there are only these two ways to create properties inside class, am I right?

It will be handy to find the changelog of such Swift syntax language updates.


Solution

  • Actually, something like var usernameField : UITextField is a perfectly valid property declaration in Swift, even though it isn't declared as an optional. In your version of Swift, the issue you were having is that properties annotated with @IBOutlet must be optionals.

    Changes to the Swift language may be found in the Xcode 6 beta release notes, here.

    On a side note, since you mentioned you'd updated to Xcode Beta 4, I'd like to point out that at the time of writing, Xcode Beta 5 was just released 2 days ago :)