Swift Array 合集

数组去交集

How to find the difference between two arrays

1
2
3
4
5
6
7
extension Array where Element: Hashable {
func difference(from other: [Element]) -> [Element] {
let thisSet = Set(self)
let otherSet = Set(other)
return Array(thisSet.symmetricDifference(otherSet))
}
}

使用:

1
2
3
let names1 = ["John", "Paul", "Ringo"]
let names2 = ["Ringo", "Paul", "George"]
let difference = names1.difference(from: names2)

数组去重

Swift之数组去重(去除重复元素)

如果数组内只含有基础类型的数据时,可以写两个for循环遍历,用下标取值做对比;当然也可以用集合 Set(Swift),比较方便快捷。

但是如果需要对 model 数组进行去重,则用不了 Set。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import UIKit

extension Array {

// 去重
func filterDuplicates<E: Equatable>(_ filter: (Element) -> E) -> [Element] {
var result = [Element]()
for value in self {
let key = filter(value)
if !result.map({filter($0)}).contains(key) {
result.append(value)
}
}
return result
}
}

// 基础类型去重
let arrays = ["1", "2", "2", "3", "4", "4"]
let filterArrays = arrays.filterDuplicates({$0})
print(filterArrays)

// model类的去重
let modelArrays = [Model("1"), Model("1"), Model("2"), Model("3")]
let filterModels = modelArrays.filterDuplicates({$0.name})
print(filterModels)

Swift数组去重

1
2
3
4
5
6
let arr = ["apple", "strawberry", "pear", "apple", "orange", "orange", "strawberry"]
let results = arr.enumerated().filter { (index,value) -> Bool in
return arr.firstIndex(of: value) == index
}.map {
$0.element
}

or

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 let arr = ["apple", "strawberry", "pear", "apple", "orange", "orange", "strawberry"]
arr.removeDuplicate()
// Array 扩展
public extension Array where Element: Equatable {

/// 去除数组重复元素
/// - Returns: 去除数组重复元素后的数组
func removeDuplicate() -> Array {
return self.enumerated().filter { (index,value) -> Bool in
return self.firstIndex(of: value) == index
}.map { (_, value) in
value
}
}
}

Set 操作

wift5 集合(Set)操作


Swift Array 合集
https://wonderhoi.com/2024/10/31/Swift-Array-合集/
作者
wonderhoi
发布于
2024年10月31日
许可协议