I'm trying to create a var of NSTimeInterval
without assigning a value at the time of initialization.
var elapsedTime : NSTimeInterval
Even without using it in the code at all, I get an error at the class:
Class 'myClassName' has no initializers
and it suggest I add a value of 0.0
to elapsedTime
. I don't want to add any value to it at first. What am I doing wrong, and what can I do to fix it?
Non-optional class properties must either have a default value or be initialized in your init
methods.
Using a default value:
class Foo {
var bar: NSTimeInterval = 3.14
}
Initializing in init
:
class Foo {
var bar: NSTimeInterval
init(timeInterval: NSTimeInterval) {
self.bar = timeInterval
}
}
As an optional:
class Foo {
var bar: NSTimeInterval?
}
If the property is optional, it is allowed to be nil
and therefore doesn't require being assigned a value before initialization can be complete.
If the property is non-optional, if has to have some means of getting a value during the first phase of initialization, otherwise, instances of your class would be initialized to an invalid state that Swift cannot reconcile (a non-optional property without an assigned value).
In a way, it's sort of the same error as the whole "unexpectedly found nil when unwrapping an optional", except this one can be caught at compile time and Xcode will prevent compilation of the code when your class doesn't have a means of providing your non-optional property a non-nil value.