从Swift数组中删除具有重复属性的对象 [英] Remove objects with duplicate properties from Swift array

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

问题描述

这里的问题涉及从数组中删除重复的对象:

The question here involves removing duplicate objects from an array:

从Swift中的数组中删除重复元素

相反,我需要删除本身不是重复的对象,但具有特定的重复属性的对象,例如id.

I instead need to remove objects that are not themselves duplicates, but have specific duplicate properties such as id.

我有一个包含我的Post对象的数组.每个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.

这两种方法都需要Post成为Hashable且等于

Both approaches will need Post to be Hashable and Equatable

在这里,我假设您的Post结构(或类)具有类型为Stringid属性.

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(失去原始订单)

要删除重复项,可以使用Set

let uniquePosts = Array(Set(posts))

解决方案2(保留订单)

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

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

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