比较NSIndexPath Swift

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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...