Zach Olivare - 2015 May 06
Inside of a view controller, how do I initialize one variable to the value of another?
timerStartingValue
and 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.timerValue
to whatever timerStartingValue
is set to so that when the timer begins counting down for the first time it begins from the correct value.timerValue
equal to timerStartingValue
:timerValue
inside 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 timerValue
in there.init()
being called (this time explicitly) before timerValue
is set.timerValue
before the 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.timerValue
an optional by declaring it:nil
when init()
is called. Then in viewDidLoad()
, timerValue
can be assigned to timerStartingValue
, as we have been attempting to do this whole time, with no compilation errors.timerValue
is an optional, it must be unwrapped before use later in the code.