Leo Correa Leo Correa - 4 years ago 132
Swift Question

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.

Answer Source

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
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download