Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift let is mutable in classes why?

Tags:

let

swift

Hello everyone I am trying to figure out why the swift code below allows me to assign a new value to the wee string in my class. I thought let was immutable but it works here. Can someone please explain this. Thanks.

import Foundation


class MyClass {
    let wee:String

    init?(inInt:Int) {
        let j:String = "what"
        //j = "I shouldn't be able to do this wiht let" // error rightly so
        //println(j)
        self.wee = "wow"
        if inInt != 2 {
            return nil
        }
        self.wee = "hey"
        self.wee = "blas" // I shouldn't be able to do this
    }


}

if let myClass:MyClass = MyClass(inInt: 2) {
    myClass.wee // prints blas
}
like image 560
Jason Hanneman Avatar asked Mar 16 '23 16:03

Jason Hanneman


1 Answers

The "Modifying Constant Properties During Initialization" heading under the Initialization section of The Swift Programming Language says:

You can modify the value of a constant property at any point during initialization, as long as it is set to a definite value by the time initialization finishes.

Reading between the lines, and considering your example, it sounds very much like restrictions on setting the value of a constant don't apply to initialization. Further evidence supporting that idea appears earlier in the same section:

When you assign a default value to a stored property, or set its initial value within an initializer, the value of that property is set directly, without calling any property observers.

It's not unlikely that the constancy of a stored property is enforced by the accessors for that property. If those accessors aren't used during initialization, then it makes sense that you can modify even a constant property as many times as you like during initialization.

The fact that you can't modify j in your example after first setting it is due to the fact that j is a local constant, not a property. There probably aren't any accessors for j at all -- instead the compiler probably enforces access rules for local constants/variables.

like image 66
Caleb Avatar answered Mar 28 '23 13:03

Caleb