Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

ios - Remove duplicate structs in array based on struct property in Swift

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 Strings are much less efficient than Ints 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...