在Swift中从数组中删除重复的元素 [英] Removing duplicate elements from an array in Swift
问题描述
现在,在Swift中,您只需键入 Set( yourArray )
即可使数组唯一. (或按需订购).
Nowadays in Swift you simply type Set( yourArray )
to make an array unique. (Or an ordered set if needed.)
在那之前,它是怎么做到的?
Before that was possible, how was it done?
我可能有一个如下所示的数组:
I might have an array that looks like the following:
[1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]
或者,实际上,是数据的相似类型部分的任何序列.我要做的是确保每个相同元素中只有一个.例如,上面的数组将变为:
Or, really, any sequence of like-typed portions of data. What I want to do is ensure that there is only one of each identical element. For example, the above array would become:
[1, 4, 2, 6, 24, 15, 60]
请注意,删除了2、6和15的重复项以确保每个相同元素中只有一个. Swift是否提供一种轻松实现此目的的方法,还是我必须自己做?
Notice that the duplicates of 2, 6, and 15 were removed to ensure that there was only one of each identical element. Does Swift provide a way to do this easily, or will I have to do it myself?
推荐答案
您可以自己滚动,例如像这样(已针对带有设置的Swift 1.2更新):
You can roll your own, e.g. like this (updated for Swift 1.2 with Set):
func uniq<S : SequenceType, T : Hashable where S.Generator.Element == T>(source: S) -> [T] {
var buffer = [T]()
var added = Set<T>()
for elem in source {
if !added.contains(elem) {
buffer.append(elem)
added.insert(elem)
}
}
return buffer
}
let vals = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]
let uniqueVals = uniq(vals) // [1, 4, 2, 6, 24, 15, 60]
Swift 3版本:
Swift 3 version:
func uniq<S : Sequence, T : Hashable>(source: S) -> [T] where S.Iterator.Element == T {
var buffer = [T]()
var added = Set<T>()
for elem in source {
if !added.contains(elem) {
buffer.append(elem)
added.insert(elem)
}
}
return buffer
}
并作为Array
的扩展名:
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
}
}
这篇关于在Swift中从数组中删除重复的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!