简体   繁体   中英

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.

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
  }
}
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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM