0

With one of the recent Xcode updates it keeps telling my to try and use "let" rather than "var". Why? I would have thought "var" would be the best to use and to only use "let" in specific situations.

HeeHeeHaha
  • 139
  • 1
  • 1
  • 8
  • IIRC, `let` is exclusively for constants, `var` for variables. perhaps xcode is seeing that you do not change a particular variable anywhere, and assumes it should be a constant? – CollinD Oct 02 '15 at 15:27
  • 4
    From [The Swift Programming Language](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID310): "If a stored value in your code is not going to change, always declare it as a constant with the let keyword. Use variables only for storing values that need to be able to change." – Eric Aya Oct 02 '15 at 15:41

2 Answers2

4

It is the opposite that is true, let is safer.

With let the developer is explicitly stating that the value is a constant that should not change and the compiler insures this, it enforces the developers concept of the usage.

With var the developer is explicitly stating that the value can change, that change is expected. In the case that the value is not changed the compiler is notifying the developer of this and that the developer can (should) change to let.

By the compiler enforcing this the code base is safer from inadvertent value changes.

zaph
  • 111,848
  • 21
  • 189
  • 228
3

You should always try to do the safest thing possible. If you can modify an object then you can modify it by mistake. If you can't modify an object then you can't modify it by mistake. Therefore if you don't want to modify an object or value you should use "let" and not "var".

Or look at it the other way round: If you use "var" you declare you intend to modify the value. If you don't modify the value, it may be because you used the wrong variable name. Say you have var x and var y, then you write x = 100 and x = 200. You used the wrong identifier in the second case. The compiler detects that your intent and actions were different.

gnasher729
  • 51,477
  • 5
  • 75
  • 98