我有一个包含我的Post对象的数组.每个人Post都有id房产.
有没有一种更有效的方法来查找我的数组中的重复帖子ID
for post1 in posts {
for post2 in posts {
if post1.id == post2.id {
posts.removeObject(post2)
}
}
}
Run Code Online (Sandbox Code Playgroud)
Luc*_*tti 30
我将建议2个解决方案.
这两种方法都需要Post是Hashable和Equatable
在这里,我假设您的Poststruct(或类)具有id类型的属性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
}
Run Code Online (Sandbox Code Playgroud)
要删除重复,您可以使用 Set
let uniquePosts = Array(Set(posts))
Run Code Online (Sandbox Code Playgroud)
var alreadyThere = Set<Post>()
let uniquePosts = posts.flatMap { (post) -> Post? in
guard !alreadyThere.contains(post) else { return nil }
alreadyThere.insert(post)
return post
}
Run Code Online (Sandbox Code Playgroud)
mar*_*izi 15
您可以创建一个空数组“uniquePosts”,并循环遍历您的数组“Posts”以将元素附加到“uniquePosts”,并且每次附加时都必须检查是否已经附加了元素。方法“包含”可以帮助你。
func removeDuplicateElements(post: [Post]) -> [Post] {
var uniquePosts = [Post]()
for post in posts {
if !uniquePosts.contains(where: {$0.postId == post.postId }) {
uniquePosts.append(post)
}
}
return uniquePosts
}
Run Code Online (Sandbox Code Playgroud)
小智 8
保留原始顺序的通用解决方案是:
extension Array {
func unique(selector:(Element,Element)->Bool) -> Array<Element> {
return reduce(Array<Element>()){
if let last = $0.last {
return selector(last,$1) ? $0 : $0 + [$1]
} else {
return [$1]
}
}
}
}
let uniquePosts = posts.unique{$0.id == $1.id }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23404 次 |
| 最近记录: |