Conditions and initialization

Hey, guys. Have a question. In a production codebase wrote something like this:

var someCondition: Bool  // upper in the function, it is initialized at that time

let someConst: Bool
if someCondition {
    someConst = true
}

print("The results \(someCondition ? someConst : false)")

And was very surprised when the compiler gave me an error. Therefore have a question. Maybe I'm doing something wrong ? Or maybe I can do something about this ?

PS. I already wrote some workaround about this, but the question seems intresting

You just declared the variable. It's not initialized. That's why it failed to compile.

Yeah, but inside the if statement I've initialized it

It is possible to declare a variable as a constant and initialize it later, before being used. But that initialization must be done for all possible code paths (and exactly once). In your case the problem is that someConst is not initialized if someCondition is false:

let someConst: Bool
if someCondition {
    someConst = true
} else {
    someConst = false
}

// Now someConst is guaranteed to be initialized ...

Apparently the compiler is not smart enough to recognize that in

print("The results \(someCondition ? someConst : false)")

the value of someConst is only accessed if someCondition is true.

1 Like

Are you asking compilation failure about someCondition or someConst? If it's the latter, see Martin's answer.

Yeah, that's pretty the answer. But still I have one more point.

Even if you initialize someCondition with a value. Compiler will reject to compile

I understand, that's because compiler cannot go through all of the conditional branches. But maybe we have some Proposal for this and I can look through and maybe help ?

You didn't show the error.

In the following fragment compiler is not smart enough:

let someConst: Bool
if true {
    someConst = true
}
if true {
    print(someConst) // Error: Constant 'someConst' used before being initialized
}

But that's not a big deal, IMHO.