Search code examples
swiftimmutability

Make variable immutable after initial assignment


Is there a way to make a variable immutable after initializing/assigning it, so that it can change at one point, but later become immutable? I know that I could create a new let variable, but is there a way to do so without creating a new variable?

If not, what is best practice to safely ensure a variable isn't changed after it needs to be? Example of what I'm trying to accomplish:

var x = 0         //VARIABLE DECLARATION


x += 1           //VARIABLE IS CHANGED AT SOME POINT


x = let x        //MAKE VARIABLE IMMUTABLE AFTER SOME FUNCTION IS PERFORMED


x += 5          //what I'm going for: ERROR - CANNOT ASSIGN TO IMMUTABLE VARIABLE

Solution

  • You can initialize a variable with an inline closure:

    let x: Int = {
        var x = 0
    
        while x < 100 {
            x += 1
        }
    
        return x
    }()