比较NSIndexPath Swift

前端之家收集整理的这篇文章主要介绍了比较NSIndexPath Swift前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我为UITableView声明了一个NSIndexPath常量,使用==运算符进行比较是否有效?

这是我一贯的声明:

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

然后我的功能

  1. override func tableView(tableView: UITableView!,heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
  2. var height: CGFloat = 45
  3.  
  4. if indexPath == DepartureDatePickerIndexPath{
  5. height = departureDatePickerShowing ? 162 : 0
  6. } else if indexPath == ArrivalDatePickerIndexPath {
  7. height = arrivalDatePickerShowing ? 162 : 0
  8. }
  9.  
  10. return height
  11. }

这当然可以正常工作,但是安全吗?我假设,因为它的工作,NSIndexPath对象上的==运算符是比较部分和行属性而不是实例。

我们来做一个非常简单的测试:
  1. import UIKit
  2.  
  3. var indexPath1 = NSIndexPath(forRow: 1,inSection: 0)
  4. var indexPath2 = NSIndexPath(forRow: 1,inSection: 0)
  5. var indexPath3 = NSIndexPath(forRow: 2,inSection: 0)
  6. var indexPath4 = indexPath1
  7.  
  8. println(indexPath1 == indexPath2) // prints "true"
  9. println(indexPath1 == indexPath3) // prints "false"
  10. println(indexPath1 == indexPath4) // prints "true"
  11.  
  12. println(indexPath1 === indexPath2) // prints "true"
  13. println(indexPath1 === indexPath3) // prints "false"
  14. println(indexPath1 === indexPath4) // prints "true"

是的,可以安全地使用==与NSIndexPath

作为一个附注,在Swift中的==总是值得比较。 ===用于检测何时两个变量引用完全相同的实例。有趣的是,indexPath1 === indexPath2显示,NSIndexPath被构建为在值匹配时共享同一个实例,所以即使你在比较实例,它仍然是有效的。

猜你在找的Swift相关文章