I really don't want people to just take an answer because it's the only one, that's why I'm showing you how you can use the power of sets. Sets are used wherever it doesn't make sense to have more than one, either it's there or not. Sets provide fast methods for checking whether an element is in the set (contains
), removing an element (remove
), combining two sets (union
) and many more. Often people just want an array because they're familiar with it, but often a set is really what they need. With that said, here is how you can use a set:
struct Model : Hashable {
var id : String?
var hashValue: Int {
return id?.hashValue ?? 0
}
}
func ==(l: Model, r: Model) -> Bool {
return l.id == r.id
}
let modelSet : Set = [
Model(id: "a"),
Model(id: "hello"),
Model(id: "a"),
Model(id: "test")
]
// modelSet contains only the three unique Models
The only requirement for a type in order to be in a set is the Hashable
protocol (which extends Equatable
). In your case, you can just return the underlying hashValue
of the String
. If your id is always a number (which it probably is), you should change the type of id
to be an Int
, because String
s are much less efficient than Int
s and it doesn't make sense to use a String
.
Also consider storing this property somewhere, so that every time you receive new models, you can just do
modelSet.unionInPlace(newModels)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…