Home > Software engineering >  Make variable immutable after initial assignment
Make variable immutable after initial assignment

Time:03-28

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


while x < 100 {   //VARIABLE IS CHANGED AT SOME POINT
    x  = 1
}

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


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

CodePudding user response:

You can initialize a variable with an inline closure:

let x: Int = {
    var x = 0

    while x < 100 {
        x  = 1
    }

    return x
}()

CodePudding user response:

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'
  • Related