如何根据Swift3中的字段检查结构是否在结构数组中? [英] how can I check if a structure is in the array of structures based on its field in Swift3?

查看:102
本文介绍了如何根据Swift3中的字段检查结构是否在结构数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的swift应用中,我有一个结构:

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? = ""
}

然后我创建一个数组:

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

但是它没有用,所以我认为由于我有唯一的id,因此我可以使用该字段比较对象.但是在这种情况下,我不知道如何比较结构的字段.你能帮我吗?

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?

推荐答案

除了在Array中不存在对象之前,无需创建MyStruct对象,而是需要创建该对象.另外建议,在MyStruct中创建一个init方法,如init(coordinate: CLLocationCoordinate2D, name: String, id: String),这样可以减少换行中每个实例属性的初始化代码.

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

这篇关于如何根据Swift3中的字段检查结构是否在结构数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆