pra*_*rad 12 arrays swift swift2
基本上我需要一个版本appendContentsOf:不附加重复元素.
例
var a = [1, 2, 3]
let b = [3, 4, 5]
a.mergeElements(b)
//gives a = [1, 2, 3, 4, 5] //order does not matter
Run Code Online (Sandbox Code Playgroud)
Ole*_*huk 26
简单地说
let unique = Array(Set(a + b))
Run Code Online (Sandbox Code Playgroud)
Ale*_*nov 12
Swift 5 更新
如果您需要组合多个数组。
func combine<T>(_ arrays: Array<T>?...) -> Set<T> {
return arrays.compactMap{$0}.compactMap{Set($0)}.reduce(Set<T>()){$0.union($1)}
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
1.
let stringArray1 = ["blue", "red", "green"]
let stringArray2 = ["white", "blue", "black"]
let combinedStringSet = combine(stringArray1, stringArray2)
// Result: {"green", "blue", "red", "black", "white"}
Run Code Online (Sandbox Code Playgroud)
let numericArray1 = [1, 3, 5, 7]
let numericArray2 = [2, 4, 6, 7, 8]
let numericArray3 = [2, 9, 6, 10, 8]
let numericArray4: Array<Int>? = nil
let combinedNumericArray = Array(combine(numericArray1, numericArray2, numericArray3, numericArray4)).sorted()
// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Run Code Online (Sandbox Code Playgroud)
这通常称为union,在Swift中可以使用Set:
let a = [1, 2, 3]
let b = [3, 4, 5]
let set = Set(a)
let union = set.union(b)
Run Code Online (Sandbox Code Playgroud)
然后你可以将集合转换为数组:
let result = Array(union)
Run Code Online (Sandbox Code Playgroud)
斯威夫特 4.0 版本
extension Array where Element : Equatable {
public mutating func mergeElements<C : Collection>(newElements: C) where C.Iterator.Element == Element{
let filteredList = newElements.filter({!self.contains($0)})
self.append(contentsOf: filteredList)
}
}
Run Code Online (Sandbox Code Playgroud)
如前所述:传递给函数的数组是将从最终数组中省略的对象数组
| 归档时间: |
|
| 查看次数: |
12719 次 |
| 最近记录: |