Illegal Argument Illegal Argument - 1 year ago 92
iOS Question

How to initialize variable in viewDidLoad() Swift2

I am trying to create a stopWatch app as a part of learning swift. Coming from Java I am having a hard time figuring out how to initialize a variable. Relevant code of viewcontroller:

var timerRunning = false

var timer: NSTimer = NSTimer() //first initialization I want to remove this initialization and leave it as nil

override func viewDidLoad() {
// second initialization
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.timeChanged), userInfo: nil, repeats: true)

func timeChanged(){
print("1 second")

The problem I am facing is double initialization of the timer variable which I think is redundant and cannot set to nil. My goal is to use timer variable in a couple of functions and initialize it on a button pressed event. The above approach works but I am looking for some cleaner/correct implementations.
Thank You

Answer Source

Declare your timer variable as optional so that initially it will have nil value and later on you can instantiate it on button event.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download