我将建议2个解决方案.
这两种方法都需要Post
是Hashable
和Equatable
在这里,我假设您的Post
struct(或类)具有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 }
要删除重复,您可以使用 Set
let uniquePosts = Array(Set(posts))
var alreadyThere = Set() let uniquePosts = posts.flatMap { (post) -> Post? in guard !alreadyThere.contains(post) else { return nil } alreadyThere.insert(post) return post }