Reputation: 10338
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() {
super.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
Upvotes: 0
Views: 415
Reputation: 2693
Declare your timer variable as optional so that initially it will have nil
value and later on you can instantiate it on button event.
Upvotes: 1