Failable initialisers and unbound instance vars

I noticed that even when you have a failable initializer that fails, you're suposed to bind all instance variables. For example:


class Foo {
    let a :Int
    let b : Int
   
    init?(name: String, m: Int, n: Int){
        if name != "fistro" {
            a = m
            b = n
        }else{
            return nil
        }
    }
}


The compiler complains that a and b are not set in the else path. Who cares???


So even when the instance of Foo is not valid and will not be used, the compiler insists in having those instance variables set to something.


Is this a bug or a feature? Is there any sense in forcing you to come up with some value in this situation?


IMHO this only forces you to use Optionals when they're not necessary. Unless someone can give a good explanation for why this is a good idea, I believe this behavior should change as it's a time waste and semantically incorrect.

Replies

I think that Apple doesn't care about this example because it's a class and you didn't use guard. Use a struct and it will compile. Use guard and it will look reeeeeal good.


guard name == "fistro" else {return nil}


Chris Lattner has an answer for your question; you can find it at http://stackoverflow.com/questions/26495586/best-practice-to-implement-a-failable-initializer-in-swift

This is an implementation limitation in Swift 2.1 and earlier. It is already fixed in the compiler, and the fix will ship in Swift 2.2 sometime in the spring. If you're interested in early access, head over to http://swift.org/


-Chris

I believe this has already been changed in the open source version of Swift.


Edit: I guess even Chris Lattner's posts get held up in moderation when they contain a link, because his reply wasn't there when I posted.