(更新至Swift 3)
正如我在评论中提到的,您可以使用修改过的Daniel Kroms解决方案,该解决方案位于我们之前标记为重复的帖子中。只需使您的Post
对象可哈希(隐式等价于id
属性),并实现以下经过修改的(使用Set
而不是Dictionary
;链接方法中的字典值无论如何都没有用过)版本的Daniel Kromsuniq
函数:
func uniq<S: Sequence, E: Hashable>(_ source: S) -> [E] where E == S.Iterator.Element {
var seen = Set<E>()
return source.filter { seen.update(with: $0) == nil }
}
struct Post : Hashable {
var id : Int
var hashValue : Int { return self.id }
}
func == (lhs: Post, rhs: Post) -> Bool {
return lhs.id == rhs.id
}
var posts : [Post] = [Post(id: 1), Post(id: 7), Post(id: 2), Post(id: 1), Post(id: 3), Post(id: 5), Post(id: 7), Post(id: 9)]
print(Posts)
var myUniquePosts = uniq(posts)
print(myUniquePosts)
这将删除重复项,同时保留原始数组的顺序。
作为Sequence
扩展的辅助函数uniq
除了使用自由函数之外,我们还可以将uniq
实现为受限制的Sequence
扩展:
extension Sequence where Iterator.Element: Hashable {
func uniq() -> [Iterator.Element] {
var seen = Set<Iterator.Element>()
return filter { seen.update(with: $0) == nil }
}
}
struct Post : Hashable {
var id : Int
var hashValue : Int { return self.id }
}
func == (lhs: Post, rhs: Post) -> Bool {
return lhs.id == rhs.id
}
var posts : [Post] = [Post(id: 1), Post(id: 7), Post(id: 2), Post(id: 1), Post(id: 3), Post(id: 5), Post(id: 7), Post(id: 9)]
print(posts)
var myUniquePosts = posts.uniq()
print(myUniquePosts)
id
。最后,我们都在这里互相学习和教育,永远不要害怕提问,我们也从中学习如何提问以及下一次如何提问。 - dfrib