Zach Posten - 2015 May 06
Inside of a view controller, how do I initialize one variable to the value of another?
timerStartingValueand the current value of the timer
timerValue(which gets decremented as the timer counts down). In this way, when the timer is reset I know what to reset it to and I can also change this value during run time in the apps settings.
timerStartingValueis set to so that when the timer begins counting down for the first time it begins from the correct value.
timerValueinside of the
viewDidLoad()function. The issue with this is that a compiler error is thrown dictating that the “Class ‘ViewController’ has no initializers”. The reason for this is that the
init()function of the class needs to be able to give each variable of the class an initial value when the object is instantiated. Because this initial value isn’t given until the
viewDidLoad()function is called, which by definition must be called after the object is instantiated, this requirement is not satisfied.
init()method to the class and initialize
init()being called (this time explicitly) before
init()call then results in “Use of ‘self’ in property access ‘timerStartingValue’ before super.init initializes self”. This is saying that you’re trying to access a member of the class before the class is instantiated, which is impossible because the member doesn’t yet exist to be accessed.
timerValuean optional by declaring it:
init()is called. Then in
timerValuecan be assigned to
timerStartingValue, as we have been attempting to do this whole time, with no compilation errors.
timerValueis an optional, it must be unwrapped before use later in the code.