-1

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?

nhgrif
  • 61,578
  • 25
  • 134
  • 173
Horay
  • 1,388
  • 2
  • 19
  • 36
  • What about initializing it to 0.0 is bad for you? – Bonsaigin Aug 20 '15 at 18:21
  • I don't want it to have any value at first – Horay Aug 20 '15 at 18:23
  • 2
    Use an optional. like this: `var elapsedTime : NSTimeInterval?`. – Adam Aug 20 '15 at 18:26
  • Thanks for the comment! That error goes away, but when I assign it a value, `elapsedTime = currentTime - startTime`, and try using it, I get the following error both places: `Use of unresolved identifier 'elapsedTime'` – Horay Aug 20 '15 at 18:31

1 Answers1

3

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.

newacct
  • 119,665
  • 29
  • 163
  • 224
nhgrif
  • 61,578
  • 25
  • 134
  • 173