-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCollection+Point.swift
42 lines (37 loc) · 1.25 KB
/
Collection+Point.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
//
// Collection+Point.swift
//
// Advent of Code Tools
//
extension Collection {
public subscript(safe index: Index) -> Element? {
startIndex..<endIndex ~= index ? self[index] : nil
}
}
// read access 2D arrays using points as subscripts
extension Collection where Element: Collection, Index == Int, Element.Index == Int {
public subscript(_ index: Point) -> Element.Element {
self[index.y][index.x]
}
public subscript(safe index: Point) -> Element.Element? {
self[safe: index.y]?[safe: index.x]
}
}
// write access 2D arrays using points as subscripts
extension MutableCollection where Element: MutableCollection, Index == Int, Element.Index == Int {
public subscript(_ index: Point) -> Element.Element {
get { self[index.y][index.x] }
set { self[index.y][index.x] = newValue }
}
public subscript(safe index: Point) -> Element.Element? {
get { self[safe: index.y]?[safe: index.x] }
set {
guard let newValue else { return }
if startIndex ..< endIndex ~= index.y {
if self[index.y].startIndex ..< self[index.y].endIndex ~= index.x {
self[index.y][index.x] = newValue
}
}
}
}
}