let constant initialization in the control flow statements

Hi,


According to the Swift Blog (https://developer.apple.com/swift/blog/?id=22), the rule is that a let constant must be initialized before use (like a var), and that it may only be initialized, not reassigned or mutated after initialization.


let s = "foo"

can be changed to

let s : String
s = "foo"


But in a control flow statement which surrounds the above code, the compiler gives me an error that says "Cannot assign to value: 's' is a 'let' constant." For example,

if condition {
     let s = "foo"
     print(s)
}

is OK, but

if condition {
     let s : String
     s = "foo"
     print(s)
}

is an error code.


Is my understanding is right?

That is, indeed, quite strange. Notably, this only affects code at the top level of the program; the same code in a function works as expected.

func foo(condition: Bool) {
    if condition {
        let s: String 
        s = "foo"          // compiles just fine
        print(s)
    }
}

You should file a bug about this. Please post your bug number, just for the record.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Thanks for your experiment in a func.


Bug number: 22322266

Resolved as of Xcode 7.1 beta 2 - 7B75 and closed.

let constant initialization in the control flow statements
 
 
Q