how can I check if a structure is in the array of

2019-02-20 20:08发布

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 ids, 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?

3条回答
欢心
2楼-- · 2019-02-20 20:46

Shorter & simpler:

if array.index(where: {$0.id == pineOne.id}) == nil {
   array.append(pineOne)
}
查看更多
等我变得足够好
3楼-- · 2019-02-20 20:59
if(array.contains({$0.id==pinOne.Id}))
{
   array.addElement(pinOne);
}
查看更多
该账号已被封号
4楼-- · 2019-02-20 21:04

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)
}
查看更多
登录 后发表回答