Search code examples
swiftswift-playground

Why is this variable not initialized when conditional statement is always entered?


Running this code results in the error "Variable 'message' used before being initialized" on the last line.

var message: String

if true {
    message = "Hello, world"
}

println(message)

Since the if statement is always true, why does the compiler think message is not initialized? Maybe this is a bug?

This example works:

var message: String

var n = 70
if n < 50 {
    message = "n is less than 50"
} else {
    message = "n is greater than or equal to 50"
}

println(message)

Removing the else statement results in the same error as above, but this time it's expected, since n may potentially be be greater than or equal to 50.


Solution

  • That is not a bug.

    The compiler did not consider the current result of the expression inside the if statement. What compiler understand is that this if statement can be false also.

    So if it is false, then using message variable println(message) is a compilation error.

    This can be ignore also depending on the warning level of your compiler, this kind of warning can be ignore or not. Check your compiler settings.