1

I have the following class:

class Foo {
    let a : Int?
    let b : Int?

    init?(){

    }
}

I get the error "constant self.a used before being initialised" in the failable initialiser. What on earth is the compiler talking about? I haven't used a at all yet!

cfischer
  • 24,452
  • 37
  • 131
  • 214
  • 1
    i agree, that is really stupid message ... so or so, you constants a and b must be initialized before the constructor returns (valid class instance, or nil) – user3441734 Dec 07 '15 at 16:43

1 Answers1

3

The problem is that each property declared with let in a class must be populated before the init does return.

In your case the init is not populating the 2 constant properties.

In Swift 2.1 each constant property of a class must be populated even when a failable initializer does fail.

class Foo {
    let a: Int?
    let b: Int?

    init?() {
        return nil // compile error
    }
}

More details here.

Struct

On the other hand you can use a struct where a failable initializer can return nil without populating all the let properties.

struct Person {
    let name: String

    init?(name:String?) {
        guard let name = name else { return nil }
        self.name = name
    }
}
Community
  • 1
  • 1
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • @cfisher: look at the link I added at the end of my answer, there is the answer provided by Chris Lattner (the creator of Swift) – Luca Angeletti Dec 07 '15 at 16:48