2

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

2 Answers 2

4

You can initialize a variable with an inline closure:

let x: Int = {
    var x = 0

    while x < 100 {
        x += 1
    }

    return x
}()
Sign up to request clarification or add additional context in comments.

3 Comments

While this sort of solves the example given, I'm struggling to see it's real-world benefit, as it still initialises the variable in a single action to a pre-determined value, and it can't be used prior to this or modified in any different way. This to me is the same as just let x = 100 but using more code. What am I missing?
@flanker in real world you can have more complex calculations, which cannot be reduced to a constant that easily.
Oh agreed, and do it all the time, esp for UI. I meant in the context of the question where I read it as wanting to initialise it to a value (0 above), change it at some indeterminate later point (to 100 in the example), and then make it immutable. But OP seems happy with your answer so I guess I'm misreading the question's intent. Thanks all the same.
4

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.