问题描述
在我的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 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?
推荐答案
除了在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中的字段检查结构是否在结构数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!