Shooonya

Technology | Books | Photography

29 Aug 2016

Understanding Swift: let

Here is the handler code for a slider in XCode 7

@IBAction func handleSlider(sender: UISlider) {
    var value = sender.value
    print("value \(value) ")
}

If you type in this code, XCode will issue the following warning near the declaration of the var value, Variable ‘value’ was never mutated; consider changing to ‘let’ constant. Once you choose that option, the code changes to this and the warning disappears.

@IBAction func handleSlider(sender: UISlider) {
    let value = sender.value
    print("value \(value) ")
}

Using let instead of var conveys that the variable is immutable. The value is set once and never changed. If you are reading someone else’s code and encounter let, you can be assured that the value of this variable is not changing in the code.

This works for collection classes and arrays as well.  If you use let before an array or dictionary, then you cannot add or remove contents from it.

For example here is a piece of code that will give an error because someInts is declared as immutable

let someInts = [Int]()
someInts.append(3)

The same is true in this case as well

let namesOfIntegers = [Int:String]()
namesOfIntegers[16] = "sixteen"