【问题标题】:Comparing NSIndexPath Swift比较 NSIndexPath Swift
【发布时间】:2014-09-30 02:31:25
【问题描述】:

如果我为 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 对象上的== 运算符正在比较节和行属性而不是实例。

【问题讨论】:

    标签: swift nsindexpath


    【解决方案1】:

    使用 Swift,您可以使用 NSIndexPathIndexPath。两者都有相同的比较策略。


    #1。 NSIndexPath

    根据 Apple 文档,NSIndexPath 符合 Equatable 协议。因此,您可以使用==!= 运算符来比较NSIndexPath 的两个实例。


    #2。 IndexPath

    Apple 文档说明了 NSIndexPathIndexPath

    Foundation 框架的 Swift 覆盖提供了 IndexPath 结构,该结构桥接到 NSIndexPath 类。

    这意味着,作为NSIndexPath 的替代方案,从Swift 3 和Xcode 8 开始,您可以使用IndexPath。注意IndexPath 也符合Equatable 协议。因此,您可以使用==!= 运算符来比较它的两个实例。

    【讨论】:

      【解决方案2】:

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

      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 被构建为在值匹配时共享同一个实例,因此即使您在比较实例,它仍然是有效的。

      【讨论】:

      • 谢谢。只是想确定一下。如果是 Objective-C,== 运算符会比较实例?
      • @Shan,这是正确的。那是因为== 实际上是在 C 中定义的。所以你正在比较 Objective-C 中的两个指针(两个变量指向内存中的同一个位置)。 Swift 离开了 C,所有类都必须定义自己的 == 运算符。所有 NSObject 实例都使用 Objective-C 中的 isEqual: 进行 == 比较
      • 我想这也适用于集合视图索引路径(有 item 而不是 row
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      相关资源
      最近更新 更多