4 ms·
> “Immutable variables”… (from the GitHub link) This is something I will never understand. Why is this not a constant (e.g. “Const”) instead? is there a diff
by MR4D 4y ago
> “Immutable variables”… (from the GitHub link)
This is something I will never understand. Why is this not a constant (e.g. “Const”) instead? is there a difference, and how should someone new to the language understand how to use one over the other ?
- layer8 4y agoThe traditional distinction is that a constant has the same value each time an expression referencing the constant is evaluated (hence a compiler for example can apply constant propagation), whereas the value of a variable referenced in an expression may be different each time the expression is evaluated. The most common example is a local variable, which, even if immutable, will often have a different value for each invocation of the containing function. This is most obvious for function parameters. With constants, you could replace each occurrence of the constant with its actual value in the program code, without changing the program semantics. With variables you generally cannot do that, because the value will vary at runtime. Constants can be in ROM, variables need to be in RAM.
- CyberDildonics 4y agoThey weren't asking about the difference between constants and variables, they were asking about the github link, which talks about using two different variable declarations, one of which can make a variable into a constant while the constant is in scope.
- layer8 4y agoI don’t think so. The example on the GitHub page is: var p1 = ... let p2 = p1 Where p1 is a mutable variable and p2 is an immutable variable. The GP asks why it isn’t called a constant instead of an immutable variable, which is what I explained.
- deleted 4y ago[deleted]
- agildehaus 4y agoThere's no difference that I'm aware of in Swift. There is in Rust, where a const is a compile-time value but an immutable variable is a value that can be defined anytime and then its immutability is enforced by the compiler.
- dabrahams 4y agoWe've been using the word "binding" in our more formal work (see the specification repo, which is more up-to-date than the README), and having clarified that for ourselves, we will probably stop talking about "immutable variables." A constant is declared with "let" and a non-constant is declared with "var", like in Swift. HTH