从Swift数组中删除具有重复属性的对象 [英] Remove objects with duplicate properties from Swift array
问题描述
这里的问题涉及从数组中删除重复的对象:
The question here involves removing duplicate objects from an array:
相反,我需要删除本身不是重复的对象,但具有特定的重复属性的对象,例如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
结构(或类)具有类型为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(失去原始订单)
要删除重复项,可以使用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屋!