删除数组中的重复对象

Osc*_*and 12 ios swift

我有一个包含我的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个解决方案.

这两种方法都需要PostHashable和Equatable

使帖子符合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)

解决方案1(丢失原始订单)

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

let uniquePosts = Array(Set(posts))
Run Code Online (Sandbox Code Playgroud)

解决方案2(保留订单)

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)

  • 谢谢您的回答。可悲的是,顺序对我很重要,因为我希望帖子按时间顺序显示。 (2认同)

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)

  • 仅代码答案被认为是低质量的:请确保提供解释您的代码的作用以及它如何解决问题。 (3认同)

小智 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)