删除数组中的重复对象 [英] Remove duplicate objects in an array

查看:104
本文介绍了删除数组中的重复对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 Post 对象的数组。每个帖子都有 id 属性。

I have an array containing my Post objects. Every Post has an id property.

是否有更有效的方法可以在我的数组中找到重复的帖子ID而不是

Is there a more effective way to find duplicate Post ID's in my array than

for post1 in posts {
    for post2 in posts {
        if post1.id == post2.id {
            posts.removeObject(post2)
        }
    }
}


推荐答案

我要去建议2个解决方案。

I am going to suggest 2 solutions.

两种方法都需要发布 Hashable 和Equatable

Both approaches will need Post to be Hashable and Equatable

这里我假设你的发布 struct(或类)具有 String 类型的 id 属性。

Here I am assuming your Post struct (or class) has an id property of type String.

struct Post: Hashable, Equatable {
    let id: String
    var hashValue: Int { get { return id.hashValue } }
}

func ==(left:Post, right:Post) -> Bool {
    return left.id == right.id
}



解决方案1(丢失原始订单)



要删除重复,您可以使用设置

let uniquePosts = Array(Set(posts))



解决方案2(保留订单)



Solution 2 (preserving the order)

var alreadyThere = Set<Post>()
let uniquePosts = posts.flatMap { (post) -> Post? in
    guard !alreadyThere.contains(post) else { return nil }
    alreadyThere.insert(post)
    return post
}

这篇关于删除数组中的重复对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆