问题
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?
回答1:
Instead of creating object of MyStruct
before checking its existence you need to create only if its not exist in Array
. Also as a suggestion create one init
method in the MyStruct
like init(coordinate: CLLocationCoordinate2D, name: String, id: String)
will reduce your code of initialization of every instance property in new line.
open class MyStruct : NSObject {
open var coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
open var username: String? = ""
open var id: String? = ""
init(coordinate: CLLocationCoordinate2D, name: String, id: String) {
self.coordinate = coordinate
self.username = name
self.id = id
}
}
Now Check for contains like this.
if !array.contains(where: {$0.id == request.id}) {
let pinOne = MyStruct(coordinate: CLLocationCoordinate2D(latitude: request.latitude, longitude: request.longitude), name: request.username, id: request.id)
self.array.append(pinOne)
}
回答2:
if(array.contains({$0.id==pinOne.Id}))
{
array.addElement(pinOne);
}
回答3:
Shorter & simpler:
if array.index(where: {$0.id == pineOne.id}) == nil {
array.append(pineOne)
}
来源:https://stackoverflow.com/questions/40518705/how-can-i-check-if-a-structure-is-in-the-array-of-structures-based-on-its-field