Leahcim
Leahcim

Reputation: 41919

When to use a constant in Swift

I'm working through this Swift tutorial and was surprised to see the use of let cell in the tableView:cellForRowAtIndexPath method (see below). The explanation provided by the tutorial author is

Use let instead of var whenever you know the value won't change

However, won't the value of cell change in this code below for each different cell, especially if an old one isn't dequeued, and wouldn't therefore a variable be more appropriate?

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {  
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    let object = objects[indexPath.row] as Alarm
    cell.textLabel.text = object.title
    return cell
}

Can you please clarify why a constant is appropriate in that code and in what sense the value of cell isn't changing.

Upvotes: 1

Views: 221

Answers (1)

Joel Fischer
Joel Fischer

Reputation: 6597

What cell is will change, however, you have to look at the scope. That cell constant is being defined anew for every iteration of that method. That is, a new constant is created, returned, and the local constant's scope leaves, so when the next call to that method is made, and cell is defined again, it's a new constant that we are dealing with.

The rule of thumb is to always use let unless you absolutely cannot. This will help prevent you from accidentally modifying vars that you didn't want to modify.

If you were to define cell outside of the method, and then just use:

cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

Then there would definitely be an issue, since you are redefining a constant.

Upvotes: 2

Related Questions