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
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
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 ?