Why not replace the var keyword with the let mut keyword, let and var have different parts of speech

Why not replace the var keyword with the let mut keyword, let and var have different parts of speech

There would be little (if any) benefit, and it would break all Swift code everywhere. Swift does not use English grammar, so keywords do not really have parts of speech.


Strictly speaking, var isn't an English word, so it doesn't have a "part of speech". It's just a keyword whose meaning is defined by the Swift language.

There's a certain pragmatic appeal to having both be a single three letter keyword. var is well-precedented from a number of other languages. But ultimately, you simply have to pick something and use it; Swift picked var a decade ago, we're well into the "and use it" phase now.


let is also the outlier, at least for now; all the other declaration introducers are nouns. (import is a verb, but it’s not a declaration.)


Breaking changes tend to need to pass a very high bar.

If you have a time machine though, that is a fine change for pre-1.0 Swift. Plus the complimentary argument "it makes the mutable version slightly more wordy giving a slight preference for constant values, which is a nice subtle nudge towards an easier to reason about state of affairs!"

If you do have a time machine though, can I borrow it, I have a few personal matters I want to settle...I PROMISE I won't kill anyone's grandfather (really I'm just interested in "correcting" a few stock transactions, also visiting some dogs and people I can't anymore).

1 Like

I wouldn't agree. Swift promotes mutable value semantics.

Shared mutable state (as you have when everything is a class) is difficult to reason about. Value semantics fix it by ensuring that mutations only occur on unique values. I can append a value to an array or sort it in-place, with complete confidence that the operation does not affect any other parts of the program.

A lot of the hate over mutable variables simply does not apply when you have value semantics.


Granted yes that is a lot less of an issue then shared mutable state, but if you have say 25 lines of function between x being set and a use of x if it is a var struct you need to know that those 25 lines don't change x. If x is a let struct and you see x you know it is the same. If you see x₃ you know it is different (and likely related) or xβ€³ or 𝔡 -- although you may have the valid complaint "why isn't the name more descriptive of why this isn't the original x, like "xAdjustedToPreventOverburnFires" or "xAdjutedToFitFreeSpace" or something.

(I don't hate mutable variables, and will use them even outside of loop like constructs, but not if I happen to have a good new descriptive name for what I would have used a variable for in other languages...)

1 Like