-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathJSONPointer.swift
70 lines (56 loc) · 1.4 KB
/
JSONPointer.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
64
65
66
67
68
69
70
import Foundation
public struct JSONPointer {
var components: [String]
init() {
components = [""]
}
init(path: String) {
components = path
.components(separatedBy: "/")
.map {
$0.replacingOccurrences(of: "~1", with: "/").replacingOccurrences(of: "~0", with: "~")
}
}
public var path: String {
return components
.map {
$0
.replacingOccurrences(of: "~", with: "~0")
.replacingOccurrences(of: "/", with: "~1")
}
.joined(separator: "/")
}
func resolve(document: Any) -> Any? {
if components.isEmpty {
return document
}
var instance = document
for component in components[1...] {
if let document = instance as? [String: Any], let value = document[component] {
instance = value
continue
}
if let document = instance as? [Any], let index = UInt(component), index < document.count {
instance = document[Int(index)]
continue
}
return nil
}
return instance
}
mutating func push(_ component: String) {
components.append(
component
.replacingOccurrences(of: "~1", with: "/")
.replacingOccurrences(of: "~0", with: "~")
)
}
mutating func pop() {
components.removeLast()
}
}
func + (lhs: JSONPointer, rhs: String) -> JSONPointer {
var pointer = lhs
pointer.components.append(rhs)
return pointer
}