forked from lixiang1994/AttributedString
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayExtension.swift
53 lines (46 loc) · 1.86 KB
/
ArrayExtension.swift
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
//
// ArrayExtension.swift
// ┌─┐ ┌───────┐ ┌───────┐
// │ │ │ ┌─────┘ │ ┌─────┘
// │ │ │ └─────┐ │ └─────┐
// │ │ │ ┌─────┘ │ ┌─────┘
// │ └─────┐│ └─────┐ │ └─────┐
// └───────┘└───────┘ └───────┘
//
// Created by Lee on 2020/7/4.
// Copyright © 2020 LEE. All rights reserved.
//
extension Array {
/// 过滤重复元素
/// - Parameter path: KeyPath条件
func filtered<E: Equatable>(duplication path: KeyPath<Element, E>) -> [Element] {
return reduce(into: [Element]()) { (result, e) in
let contains = result.contains { $0[keyPath: path] == e[keyPath: path] }
result += contains ? [] : [e]
}
}
/// 过滤重复元素
/// - Parameter closure: 过滤条件
func filtered<E: Equatable>(duplication closure: (Element) throws -> E) rethrows -> [Element] {
return try reduce(into: [Element]()) { (result, e) in
let contains = try result.contains { try closure($0) == closure(e) }
result += contains ? [] : [e]
}
}
/// 过滤重复元素
/// - Parameter path: KeyPath条件
@discardableResult
mutating func filter<E: Equatable>(duplication path: KeyPath<Element, E>) -> [Element] {
self = filtered(duplication: path)
return self
}
/// 过滤重复元素
/// - Parameter closure: 过滤条件
@discardableResult
mutating func filter<E: Equatable>(duplication closure: (Element) throws -> E) rethrows -> [Element] {
self = try filtered(duplication: closure)
return self
}
}
extension Array where Element: Equatable {
}