数组可以是任何类型,如
let myArray1 = [ 1, 2, 3, 1, 2, 1, 3, nil, 1, nil]
let myArray2 = [ 1, 2.0, 1, 3, 1.0, nil]
从数组中删除重复值后,新数组应为:
输出
[ 1, 2, 3, nil ]
答案 0 :(得分:3)
@ Daniel的解决方案作为通用函数:
func uniqueElements<T: Equatable>(of array: [T?]) -> [T?] {
return array.reduce([T?]()) { (result, item) -> [T?] in
if result.contains(where: {$0 == item}) {
return result
}
return result + [item]
}
}
let array = [1,2,3,1,2,1,3,nil,1,nil]
let r = uniqueElements(of: array) // [1,2,3,nil]
答案 1 :(得分:2)
您可以使用此缩小功能删除重复的条目:
myArray.reduce([Int?]()) { (result, item) -> [Int?] in
if result.contains(where: {$0 == item}) {
return result
}
return result + [item]
}
输出:[1, 2, 3, nil]
答案 2 :(得分:2)
请检查此代码,我在获取过滤后的数组后使用了NSArray,可以将其转换为swift数组
let arr = [1, 1, 1, 2, 2, 3, 4, 5, 6, nil, nil, 8]
let filterSet = NSSet(array: arr as NSArray as! [NSObject])
let filterArray = filterSet.allObjects as NSArray //NSArray
print("Filter Array:\(filterArray)")