What's wrong with comparing an optional bool in a single if structure in swift

I programmed for a while in Swift, and I think I had to put it! on all variables of the let field that were not defined immediately.

Now I notice today that this piece of code does not compile, and am I really surprised? Why is this?

class MyClass : Mapper {
    var a: Bool!

    required init?(_ map: Map) {
    }

    // Mappable
    func mapping(map: Map) {
        a   <- map["a"]
    }
}

let myClass = MyClass()

if myClass.a { // Compiler not happy
    //  Optional type 'Bool!' cannot be used as a boolean; test for '!= nil' instead
}

if true && myClass.a { // Compiler happy

}

if myClass.a && myClass.a { // Compiler happy

}

Apple Swift version 2.2

Edit
Some people indicate why I use letfor a variable that will never change. I mentioned that this is for field variables, but I'm shortening the example. When using ObjectMapper ( http://github.com/Hearst-DD/ObjectMapper ) all fields are not defined immediately in init. Is that why they are all optional? or required!

+4
2

...

Swift 1.0 , optVar , :

if optVar {
    println("optVar has a value")
} else {
    println("optVar is nil")
}

Swift Programming Swift 1.1 ( 2014-10-16) :

true, false, , Bool. nil == !=, , .

, , , Swift :

if a {
}

:

if a != nil {
}

nil, , a .

, Swift , a:

if a! {
}

true:

if a == true {
}

( ):

if a ?? false {
    print("this will not crash if a is nil")
}
+1

let a: Bool ! true false. , , , .

.

let a: Bool

a = true

if a { // Compiler happy

}

, a .

let a: Bool

if thingOne < thingTwo {
    a = true
} else {
    a = false
}

if a { // Compiler happy

}

, a , .

let a: Bool

if thingOne < thingTwo {
    a = true
}

if a { // Compiler NOT happy
    // "Constant 'a' used before being initialized"
}

, , ​​ , var, .

var a: Bool?

if a == true { // Compiler happy

}
+3

All Articles