如何在Swift中检查我的NSObject数组是否包含特定的NSObject?

时间:2017-03-21 22:35:37

标签: swift nsarray nsobject

在我的Swift应用中,我有一个班级:

open class CustomCluster : NSObject {

    open var coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
    open var title: String? = ""
    open var amount: Int = 0 
}

extension CustomCluster : MKAnnotation {

}

现在,我正在创建一个存储该类型对象的数组:

var array:[CustomCluster] = []

并追加这样的对象:

let pinOne = CustomCluster()

pinOne.coordinate = CLLocationCoordinate2D(latitude: request.latitude, longitude: request.longitude)
pinOne.amount = request.amount
   if(!self.array.contains(pinOne))
   {
      self.array.append(pinOne);
   }

问题是,即使坐标和数量与之前添加的集群相同,这一行:

if(!self.array.contains(pinOne))

不能正常工作并允许向阵列添加另一个引脚(即使已经有一个具有相同精确数据的引脚)。

如何将具有相同坐标和数量的新对象排除在添加到我的数组之外?

===

所以我刚刚添加了一个函数:

static func == (lcc: CustomCluster, rcc: CustomCluster) -> Bool {
    return
        lcc.coordinate.latitude == rcc.coordinate.latitude &&
            lcc.coordinate.longitude == rcc.coordinate.longitude &&
            lcc.amount == rcc.amount
}

但问题仍然存在,我还缺少其他什么吗?

1 个答案:

答案 0 :(得分:1)

正如Hamish在继承NSObject时在评论中已经提到的,当符合Equatable协议时,你需要覆盖isEqual方法。试试这样:

class CustomCluster: NSObject, MKAnnotation {
    var coordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0)
    var title: String? = ""
    var amount: Int = 0
    override func isEqual(_ object: Any?) -> Bool {
        return coordinate.latitude == (object as? CustomCluster)?.coordinate.latitude &&
               coordinate.longitude == (object as? CustomCluster)?.coordinate.longitude &&
               title == (object as? CustomCluster)?.title &&
               amount == (object as? CustomCluster)?.amount
    }
}