user3766930
user3766930

Reputation: 5829

how can I check if my array of NSObjects contains a specific NSObject in Swift?

In my Swift app I have a class:

open class CustomCluster : NSObject {

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

extension CustomCluster : MKAnnotation {

}

Now, I'm creating an array that stores some objects of that type:

var array:[CustomCluster] = []

and append objects like this:

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);
   }

The problem is, that even in case when coordinate and amount is the same as in a previously added cluster, this line:

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

doesn't work well and allow adding another pin to the array (even though there is already a pin with the same exact data).

How can I exclude new objects with the same coordinates and amount from adding them to my array?

===

So I just added a function:

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

but the problem still occurs, is there anything else that I'm missing here?

Upvotes: 2

Views: 536

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236360

As already mentioned in comments also by Hamish when subclassing NSObject you need to override isEqual method when conforming to Equatable protocol. Try like this:

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
    }
}

Upvotes: 2

Related Questions