如果我为UITableView声明了一个NSIndexPath常量,使用==运算符进行比较是否有效?
这是我一贯的声明:
- let DepartureDatePickerIndexPath = NSIndexPath(forRow: 2,inSection: 0)
然后我的功能:
- 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
- }
这当然可以正常工作,但是安全吗?我假设,因为它的工作,NSIndexPath对象上的==运算符是比较部分和行属性而不是实例。
我们来做一个非常简单的测试:
- 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"
是的,可以安全地使用==与NSIndexPath
作为一个附注,在Swift中的==总是值得比较。 ===用于检测何时两个变量引用完全相同的实例。有趣的是,indexPath1 === indexPath2显示,NSIndexPath被构建为在值匹配时共享同一个实例,所以即使你在比较实例,它仍然是有效的。