4thSpace 4thSpace - 7 months ago 9
Swift Question

Why is "let" used instead of var?

On this page http://www.raywenderlich.com/85578/first-core-data-app-using-swift, many of the examples use let instead of var.

func tableView(tableView: UITableView,
cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {

let cell =
tableView.dequeueReusableCellWithIdentifier("Cell")
as UITableViewCell

let person = people[indexPath.row]
cell.textLabel!.text = person.valueForKey("name") as String?

return cell
}


I see this in lots of tutorials. Is there some reason to use let in the above snippet over var?

Answer

As a matter of fact, as a Swift programmer, the question to ask is why not use var over let? This is one area where Swift differs greatly in semantics from other languages such as C#.

The reason is because once you obtain a reference to a table cell, that reference is not going to change for the lifetime of each invocation of this method. There are no reassignments to cell, because there is simply no reason to do so. And therefore there is no reason to make cell a variable.

In general, in Swift, you should default to using let, and only use var if you need to reassign. Remember that let only prevents the constant itself from being reassigned; you can still mutate the object that is being referenced, as is being done in cell.textLabel!.text = person... in this case.

There are other, subtle differences that are further covered in Apple's documentation, but this applies to the majority of cases.

Comments