ios - 根据 Swift 中的结构属性删除数组中的重复结构

标签 ios iphone swift ios9 ios10

我做了一个简单的结构并实现了 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
        ...
}

然后在我的项目中我得到一个 [MyModelStruct] 数组,我要做的是删除所有具有相同 id 的 MyModelStruct

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] 

如何制作 cleanFunction ?

有人可以帮忙吗? 谢谢大家。 Xcode:版本 7.3.1

最佳答案

我真的不希望人们只接受答案,因为这是唯一的答案,这就是为什么我要向您展示如何使用集合的力量。集合用于任何没有意义的地方,无论是否存在。集合提供了检查元素是否在集合中(contains)、删除元素(remove)、合并两个集合(union)的快速方法) 还有很多。通常人们只是想要一个数组,因为他们熟悉它,但通常他们真正需要的是集合。话虽如此,以下是您如何使用集合:

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

要成为集合中的类型,唯一的要求是 Hashable 协议(protocol)(它扩展了 Equatable)。在您的情况下,您可以只返回 String 的基础 hashValue。如果您的 id 始终是一个数字(它可能是),您应该将 id 的类型更改为 Int,因为 Strings比 Int 效率低得多,使用 String 没有意义。

还可以考虑将此属性存储在某个地方,这样每次收到新模型时,您都可以这样做

modelSet.unionInPlace(newModels)

关于ios - 根据 Swift 中的结构属性删除数组中的重复结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38153674/

相关文章:

ios - 将数据从 ViewController 传递到实例化的自定义 View Controller

ios - 从Dropbox iOS Core API获取音频文件

ios - iOS“默认” UIWebView/WebKit上的WebAudio支持

ios - 如何从 ipad 内置视频应用访问视频

ios - 使用 UItableView Swift 4 的自定义单元格时的 SIGBRT

ios - 添加覆盖几个连续 UITableViewCells 的 UIButton

iphone - 在第四行末尾追加 "..."

iphone - ViewDidLoad 在 initWithNibName 之前被调用?

ios - Swift 2.2 - SpriteKit - 子类 SKSpriteNode 类

ios - 应该在什么队列上调用 completionHandler 来报告即时错误?