Comparing NSIndexPath Swift

泄露秘密 提交于 2019-12-03 04:32:40

Let's do a very simple test:

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"

Yes, it is safe to use == with NSIndexPath

As a side note, == in Swift is always for value comparisons. === is used for detecting when two variables reference the exact same instance. Interestingly, the indexPath1 === indexPath2 shows that NSIndexPath is built to share the same instance whenever the values match, so even if you were comparing instances, it would still be valid.

With Swift, you can use NSIndexPath or IndexPath. Both have the same strategy to compare.


#1. NSIndexPath

According to Apple Documentation, NSIndexPath conforms to Equatable protocol. Therefore, you can use == or != operators in order to compare two instances of NSIndexPath.


#2. IndexPath

Apple documentation states about NSIndexPath and IndexPath:

The Swift overlay to the Foundation framework provides the IndexPath structure, which bridges to the NSIndexPath class.

This means that, as an alternative to NSIndexPath, starting with Swift 3 and Xcode 8, you can use IndexPath. Note that IndexPath also conforms to Equatable protocol. Therefore, you can use == or != operators in order to compare two instances of it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!