Swift的Array的常见扩展
参考:
- https://github.com/lixiang1994/AttributedString
- https://github.com/lixiang1994/AttributedString/blob/master/Sources/Extension/ArrayExtension.swift
前言
项目中使用
Swift
的Array
场景很多,其中数据转换、过滤、分组、去重等相关方法使用很频繁,特记录下
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
extension Array {
// 将元素进行分组
func toGroupedList<E: Equatable>(closure: (Element) -> E?) -> [E: [Element]] {
return reduce(into: [E: [Element]]()) { (result, e) in
// 分组的key, 这里支持optional是为了调用时减少判断代码
if let groupKey = closure(e) {
// 之前的列表
let preList = result[groupKey] ?? []
result[groupKey] = preList + [e]
}
}
}
// 将数据转换为字典
func toDict<E: Equatable>(closure: (Element) -> E?) -> [E: Element] {
return reduce(into: [E: Element]()) { (result, e) in
// 转换为dict的key,这里支持optional是为了调用时减少判断代码
if let dictKey = closure(e) {
result[dictKey] = e
}
}
}
// 对内容进行过滤
func toDeduplicationList<E: Equatable>(closure: (Element) -> E?) -> [Element] {
return reduce(into: [Element]()) { (result, e) in
// 元素的唯一性key,这里支持optional是为了调用时减少判断代码
let uniqueKey = closure(e)
// 查询之前的列表里是否存在于当前key一样的元素
let contains = result.contains { closure($0) == uniqueKey }
// 如果已经存在该元素,不加入,如果不存在该元素,添加该元素
result = result + (contains ? [] : [e])
}
}
// 数组截取
func subArray(from: Int, size: Int) -> Array<Element> {
return self.subArray(from: from, to: from+size-1)
}
func subArray(from: Int) -> Array<Element> {
return self.subArray(from: from, to: self.count-1)
}
func subArray(to: Int) -> Array<Element> {
return self.subArray(from: 0, to: self.count-1)
}
func subArray(from: Int, to: Int) -> Array<Element> {
// 可截取的最大值
let maxTo: Int = self.count - 1
var fromIndex = from
if fromIndex < 0 {
fromIndex = 0
}
if fromIndex >= maxTo {
return []
}
var toIndex = to
if toIndex < 0 {
toIndex = 0
}
if toIndex > maxTo {
toIndex = maxTo
}
if toIndex <= fromIndex {
return []
}
return Array(self[from...toIndex])
}
}
测试Demo
1
2
3
4
5
6
7
8
9
10
11
let list = [1,2,2,3,3,6]
// 去重
let depList = list.toDeduplicationList { $0 }
// 将数字转换为字符串的字符串
let listDict = list.toDict{ "\($0)" }
// 按奇偶数数据进行分组
let groupDict = list.toGroupedList { $0 % 2 }
let subList = list.subArray(from: 2)
let mapList = list.map { $0 + 1 }
let fileterList = list.filter{ $0 > 2}
print(list, depList, listDict, groupDict, subList, mapList, fileterList)
This post is licensed under CC BY 4.0 by the author.