比较NSIndexPath Swift

Sha*_*han 24 nsindexpath swift

如果我为UITableView声明了一个NSIndexPath常量,那么使用==运算符进行比较是否有效?

这是我的不变声明:

let DepartureDatePickerIndexPath = NSIndexPath(forRow: 2, inSection: 0)
Run Code Online (Sandbox Code Playgroud)

然后我的功能:

 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
}
Run Code Online (Sandbox Code Playgroud)

这当然可以正常工作,但这样做是否安全?我假设因为它工作,==NSIndexPath对象上的运算符正在比较section和row属性而不是实例.

dre*_*wag 50

我们来做一个非常简单的测试:

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"
Run Code Online (Sandbox Code Playgroud)

是的,==与NSIndexPath 一起使用是安全的

作为旁注,==Swift总是用于价值比较.===用于检测两个变量何时引用完全相同的实例.有趣的是,indexPath1 === indexPath2显示NSIndexPath被构建为在值匹配时共享相同的实例,因此即使您比较实例,它仍然有效.