Difference Between 'Let' and 'Var' in Swift

What is the difference between `let` and `var` in Swift?

The let keyword defines a constant:

let theAnswer = 42

The theAnswer cannot be changed afterwards. This is why anything weak can't be written using let. They need to change during runtime and you must be using var instead.

The var defines an ordinary variable.

What is interesting:

The value of a constant doesn’t need to be known at compile time, but you must assign the value exactly once.

Another strange feature:

You can use almost any character you like for constant and variable
names, including Unicode characters:

let = "dogcow"

Excerpts From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewBook?id=881256329



Community Wiki

Because comments are asking for adding other facts to the answer, converting this to community wiki answer. Feel free edit the answer to make it better.

What is the different between `if var` and `if let` in swift?

If you use the let then you will not be able to change myValue.

if let myValue = myObject.value as NSString? {
myValue = "Something else" // <-- Compiler error
}

On the other hand with var you can.

if var myValue = myObject.value as NSString? {
myValue = "Something else" // <-- It's fine
}

Please note that myValue does exists only within the scope of the if and changing its value does not produce effect outside of its scope.

Hope this helps.

var vs let in Swift

Rather than constant and variable, the correct terminology in swift is immutable and mutable.

You use let when you know that once you assign a value to a variable, it doesn't change - i.e. it is immutable. If you declare the id of a table view cell, most likely it won't change during its lifetime, so by declaring it as immutable there's no risk that you can mistakenly change it - the compiler will inform you about that.

Typical use cases:

  • A constant (the timeout of a timer, or the width of a fixed sized label, the max number of login attempts, etc.). In this scenario the constant is a replacement for the literal value spread over the code (think of #define)
  • the return value of a function used as input for another function
  • the intermediate result of an expression, to be used as input for another expression
  • a container for an unwrapped value in optional binding
  • the data returned by a REST API call, deserialized from JSON into a struct, which must be stored in a database

and a lot more. Every time I write var, I ask myself: can this variable change?. If the answer is no, I replace var with let. Sometimes I also use a more protective approach: I declare everything as immutable, then the compiler will let me know when I try to modify one of them, and for each case I can proceed accordingly.

Some considerations:

For reference types (classes), immutable means that once you assign an instance to the immutable variable, you cannot assign another instance to the same variable.

For value types (numbers, strings, arrays, dictionaries, structs, enums) immutable means that that once you assign a value, you cannot change the value itself. For simple data types (Int, Float, String) it means you cannot assign another value of the same type. For composite data types (structs, arrays, dictionaries) it means you cannot assign a new value (such as a new instance of a struct) and you cannot change any of their stored properties.

Also an immutable variable has a semantic meaning for the developer and whoever reading the code - it clearly states that the variable won't change.

Last, but maybe less important from a pure development point of view, immutables can be subject to optimizations by the compiler.

what is the difference between let and var for reference types, when we create an IBOutlet programmatically in ios, swift

In your example, you're considering using var vs. let in declaring the property itself, as well as inside the closure that initialized that property. In answer to your question, bottom line, anywhere you can use let (for constants), you theoretically can use var (for variables), but you should only do so if you're planning on changing that variable later. In the case of a reference type, like UILabel, this means if you plan on replacing that label with an entirely new instance of UILabel.

So, the first and fourth options, where var was used inside the closure, can be dismissed out of hand as poor programming style because you're not changing it again within the scope of the closure, so we know we should use let inside the closure. Regarding second or third options (i.e. whether the property, itself, should be constant or variable), the question is whether you're ever going to replace that UILabel with another, later. If so, you have to use the third option. But we can suspect that this was unlikely to be your intent, and so if you don't plan on replacing that label later, of these four options, you would favor the second option of let/let.


Having said that, this looks like this is in a view controller, and I wouldn't advise instantiating any view objects during the instantiation of the view controller. Usually that's deferred to viewDidLoad or if the entire view hierarchy is built programmatically, in loadView. Or, even better, we get out of the business of building controls manually and we let the storyboard instantiate IBOutlet references at the appropriate time.

Difference between var array and let array?

since arrays in swift are structs declaring an array with let not only prevents you from assigning a new value to it but also prevents you from changing its contents

so for example:

    let arr = [0, 1, 2]
arr[0] = 10 //will not compile
arr = [] //will not compile

Swift: when should I use var instead of let?

Use let whenever you can. Use var when you must. Making things immutable makes a lot of bugs impossible, so it should be your default choice. As much as possible, set all your values in init and never change them. Similarly, you should use struct when you can, and class when you must (though in my experience this is harder to achieve than using let).

So in your example, if you cannot set A.a during initialization, then yes, it should be var. But there is no need in your example to use var for B.b. (And there's no reason in either example to use class, at least in the way you've presented the question.)



Related Topics



Leave a reply



Submit