Stoic
Stoic

Reputation: 1216

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

Upvotes: 2

Views: 395

Answers (2)

Phil Dukhov
Phil Dukhov

Reputation: 87834

You can initialize a variable with an inline closure:

let x: Int = {
    var x = 0

    while x < 100 {
        x += 1
    }

    return x
}()

Upvotes: 4

aheze
aheze

Reputation: 30318

There's no way I know of that lets you change a var variable into a let constant later on. But you could declare your constant as let to begin with and not immediately give it a value.

let x: Int /// No initial value

x = 100 /// This works.

x += 5 /// Mutating operator '+=' may not be used on immutable value 'x'

As long as you assign a value to your constant sometime before you use it, you're fine, since the compiler can figure out that it will eventually be populated. For example if else works, since one of the conditional branches is guaranteed to get called.

let x: Int

if 5 < 10 {
    x = 0 /// This also works.
} else {
    x = 1 /// Either the first block or the `else` will be called.
}

x += 5 /// Mutating operator '+=' may not be used on immutable value 'x'

Upvotes: 4

Related Questions