Comparing NSIndexPath Swift

Shan picture Shan · Aug 7, 2014 · Viewed 20.5k times · Source

If I have a NSIndexPath constant declared for a UITableView, is it valid to compare using the == operator?

This is my constant declaration:

let DepartureDatePickerIndexPath = NSIndexPath(forRow: 2, inSection: 0)

And then my function:

 override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
    var height: CGFloat = 45

    if indexPath == DepartureDatePickerIndexPath{
        height = departureDatePickerShowing ? 162 : 0
    } else if indexPath == ArrivalDatePickerIndexPath {
        height = arrivalDatePickerShowing ? 162 : 0
    }

    return height
}

This certainly works properly, but is it safe to do? I'm assuming that since it works, the == operator on the NSIndexPath object is comparing the section and row properties instead of the instance.

Answer

drewag picture drewag · Aug 7, 2014

Let's do a very simple test:

import UIKit

var indexPath1 = NSIndexPath(forRow: 1, inSection: 0)
var indexPath2 = NSIndexPath(forRow: 1, inSection: 0)
var indexPath3 = NSIndexPath(forRow: 2, inSection: 0)
var indexPath4 = indexPath1

println(indexPath1 == indexPath2) // prints "true"
println(indexPath1 == indexPath3) // prints "false"
println(indexPath1 == indexPath4) // prints "true"

println(indexPath1 === indexPath2) // prints "true"
println(indexPath1 === indexPath3) // prints "false"
println(indexPath1 === indexPath4) // prints "true"

Yes, it is safe to use == with NSIndexPath

As a side note, == in Swift is always for value comparisons. === is used for detecting when two variables reference the exact same instance. Interestingly, the indexPath1 === indexPath2 shows that NSIndexPath is built to share the same instance whenever the values match, so even if you were comparing instances, it would still be valid.