如何快速防止对象ArrayList中的重复

var firstArray = [1,2,3,4,5,6]
var secondArray = [1,2,3,7,8,9,0]

for item in secondArray {
//    some thing that i can avoid duplicate
    firstArray.append(item)
}
print(firstArray)
//end result should be firstArray = [1,2,3,4,5,6,7,8,9,0]

我想防止firstArray追加重复项

评论
零零柒
零零柒

将此扩展用于独特的元素:

extension Array where Element: Hashable {
    var uniques: Array {
        var buffer = Array()
        var added = Set<Element>()
        for elem in self {
            if !added.contains(elem) {
                buffer.append(elem)
                added.insert(elem)
            }
        }
        return buffer
    }
}

用法:

print(firstArray.uniques)
点赞
评论
zamet
zamet

要保留订单,您可以这样操作:

for item in secondArray {
    if !firstArray.contains(item) {
        firstArray.append(item)
    }
}
点赞
评论