Search code examples
xcodeswiftsyntaxvarlet

Why does Xcode keeps insisting on using let rather than var?


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.


Solution

  • 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.