Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing Swift properties that require "self" as an argument

Tags:

ios

swift

ios8

I have a Swift class that I'd like to look something like this:

class UpdateManager {
  let timer: NSTimer

  init() {
    timer = NSTimer(timeInterval: 600, target: self, selector: "check", userInfo: nil, repeats: true)
  }

  func check() {
    // Do some stuff
  }
}

However, Swift doesn't like the fact that I'm passing self to the NSTimer initializer. Am I breaking some pattern here? How is one supposed to accomplish initialization like this?

like image 298
bloudermilk Avatar asked Aug 05 '14 22:08

bloudermilk


1 Answers

You've found the primary use case of the Implicitly Unwrapped Optional.

  • You need to access self from init, before timer is initialized.
  • Otherwise, timer should never be nil, so you shouldn't have to check it outside of init.

So, you should declare let timer: NSTimer!.

like image 182
jtbandes Avatar answered Oct 11 '22 16:10

jtbandes