在SWIFT中从数组中删除重复元素我可能有一个数组,如下所示:[1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]或者,真的,任何类似类型的数据序列。我要做的是确保每个相同的元素中只有一个。例如,上面的数组将变成:[1, 4, 2, 6, 24, 15, 60]注意,删除了2、6和15的副本,以确保每个相同的元素中只有一个。SWIFT提供了一种很容易做到的方法,还是我必须自己去做?
3 回答
qq_遁去的一_1
TA贡献1725条经验 获得超8个赞
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]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}
RISEBY
TA贡献1856条经验 获得超5个赞
let unique = Array(Set(originals))
梵蒂冈之花
TA贡献1900条经验 获得超5个赞
extension Array where Element:Equatable {
func removeDuplicates() -> [Element] {
var result = [Element]()
for value in self {
if result.contains(value) == false {
result.append(value)
}
}
return result }}let arrayOfInts = [2, 2, 4, 4]print(arrayOfInts.removeDuplicates()) // Prints: [2, 4]
基于属性的滤波
extension Array {
func filterDuplicates(@noescape includeElement: (lhs:Element, rhs:Element) -> Bool) -> [Element]{
var results = [Element]()
forEach { (element) in
let existingElements = results.filter {
return includeElement(lhs: element, rhs: $0)
}
if existingElements.count == 0 {
results.append(element)
}
}
return results }}let filteredElements = myElements.filterDuplicates { $0.PropertyOne == $1.PropertyOne && $0.PropertyTwo == $1.PropertyTwo }添加回答
举报
0/150
提交
取消
