-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfinding-objects-in-arrayt-in-swift-using-key-paths.swift
64 lines (55 loc) · 1.3 KB
/
finding-objects-in-arrayt-in-swift-using-key-paths.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
54
55
56
57
58
59
60
61
62
63
// Want to support my work 🤝? https://buymeacoffee.com/vandad
import Foundation
struct Person: CustomDebugStringConvertible {
let name: String
let age: Int
var debugDescription: String { "\(name), age: \(age)" }
}
struct House: CustomDebugStringConvertible {
let address: String
let tennants: [Person]
var debugDescription: String { "House: \(address)" }
}
let houses = [
House(
address: "First address",
tennants: [
Person(name: "Foo 1", age: 20),
Person(name: "Bar 1", age: 30),
]
),
House(
address: "Second address",
tennants: [
Person(name: "Foo 2", age: 20),
Person(name: "Bar 2", age: 30),
]
),
]
extension Array {
func firstWhere<M: Equatable>(
_ keyPath: KeyPath<Self.Element, M>,
is search: M
) -> Self.Element? {
self.first(where: { (element: Self.Element) -> Bool in
element[keyPath: keyPath] == search
})
}
}
let foo1ByName = houses
.flatMap(\.tennants)
.firstWhere(
\.name,
is: "Foo 1"
)
let foo1ByAge = houses
.flatMap(\.tennants)
.firstWhere(
\.age,
is: 20
)
let secondHouse = houses
.firstWhere(
\.address,
is: "Second address"
)