Leo Correa
Leo Correa

Reputation: 19789

Swift optional or Implicit property on UIViewController subclass

I have a the following class

class Foo : UIViewController {
  var demo : SKView

  override func viewDidLoad() {
    ...
    self.demo = SKView(...)
    ...
    self.view.insertSubview(demo, atIndex: 0)
  }

  override func viewWillDisappear(animated : Bool) {
    self.demo.removeFromSuperView()
    self.demo = nil
  }
}

My question is, since I don't have an initializer on Foo, demo has to be either ? or !. I have read many places that I should stay away from using !. In this case however, is there any reason to not use it? I'm not 100% clear on the downsides specifically on this case since the view itself will always be set on viewDidLoad and only unset on viewWillDisappear.

What is the most common pattern for these kind of properties on such classes? Properties that get set on viewDidLoad and will always have a value.

Upvotes: 1

Views: 484

Answers (2)

Randy
Randy

Reputation: 2348

The reason for this is that Swift enforces class members to always have a value upon initialization. By marking the variable demo with ! or ? you are telling the compiler that this variable can have the value nil, hence the optional notation.

In the context of iOS development, it's perfectly acceptable to mark SKView with ! so you don't have to suffix each call to demo with ?.

If demo is nil and you require a value to always be present then the app will crash during runtime which under many circumstances is in fact desirable.

class Foo : UIViewController {
  var demo : SKView!

  override func viewDidLoad() {
    ...
    self.demo = SKView(...)
    ...
    self.view.insertSubview(demo, atIndex: 0)
  }

  override func viewWillDisappear(animated : Bool) {
    self.demo.removeFromSuperView()
    self.demo = nil
  }
}

Upvotes: 2

Klein Mioke
Klein Mioke

Reputation: 1352

class Foo: UIViewController {
    var demo: SKView = SKView()

    ...
}

100% it won't be nil since Foo().

Or you can override the init(), but I don't like that. If I'm sure I won't use the property before ViewDidLoad(), I prefer to writing the initialization in ViewDidLoad(), and mark as var demo: SKView!

Upvotes: 1

Related Questions