In my swift
app I have a structure:
open class MyStruct : NSObject {
open var coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
open var username: String? = ""
open var id: String? = ""
}
And I create an Array of it:
var array:[MyStruct] = []
Then I'm creating an object:
let pinOne = MyStruct()
pinOne.coordinate = CLLocationCoordinate2D(latitude: request.latitude, longitude: request.longitude)
pinOne.username = request.username
pinOne.id = request.id
and I want to add it to the array only if the array does not contain it. I tried with this:
if(!(self.array.contains(pinOne))){
self.array.append(pinOne)
}
But it didn't work, so I thought that since I have unique id
s, I could use that field for comparing objects. But I don't know how to compare fields of the structures in this case. Can you help me with that?
Shorter & simpler:
Instead of creating object of
MyStruct
before checking its existence you need to create only if its not exist inArray
. Also as a suggestion create oneinit
method in theMyStruct
likeinit(coordinate: CLLocationCoordinate2D, name: String, id: String)
will reduce your code of initialization of every instance property in new line.Now Check for contains like this.