I have made a simple struct and implemented the Equatable protocol :
extension MyModelStruct: Equatable {}
func ==(lhs: NModelMatch, rhs: NModelMatch) -> Bool {
let areEqual = lhs.id == rhs.id
return areEqual
}
public struct MyModelStruct {
var id : String?
var staticId : String?
init(fromDictionary dictionary: NSDictionary){
id = dictionary["id"] as? String
...
}
Then in my project i get an array of [MyModelStruct], what i what to do is to remove all the MyModelStruct that have the same id
let val1 = MyModelStruct(id:9, subId:1)
let val2 = MyModelStruct(id:10, subId:1)
let val3 = MyModelStruct(id:9, subId:10)
var arrayOfModel = [val1,val2,val3]; // or set but i do not know how to use a set
var arrayCleaned = cleanFunction[M2,M3]
How can i make the cleanFunction ?
Can someone help please. Thanks for all. Xcode : Version 7.3.1
Use a
Set
instead of anArray
.If you extend the Array type with this function :
You'll be able to clean up duplicates using :
without needing to make the structure Equatable.
Please note that this is not going to be efficient if your array is very large and you might want to consider filtering insertions into your array at the source if possible.
I agree you are better off using a Set. You should be able to initialize the Set using an Array, e.g., var arrayOfModel: Set = [val1, val2, val3]. But because you are using a custom type, you will need to make sure that MyModelStruct conforms to hashable. This link has a good explanation.
But if you want to use an array then you need to change
to
You need to modify your struct to have a subId property (and make the variables Int instead of String.
In answer to your question, yes you do need to iterative over the array.
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:The only requirement for a type in order to be in a set is the
Hashable
protocol (which extendsEquatable
). In your case, you can just return the underlyinghashValue
of theString
. If your id is always a number (which it probably is), you should change the type ofid
to be anInt
, becauseString
s are much less efficient thanInt
s and it doesn't make sense to use aString
.Also consider storing this property somewhere, so that every time you receive new models, you can just do