File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -4,7 +4,7 @@ import Foundation
44
55/// Simple struct used to represent multiple segments of a string.
66/// This is a utility used to recursively access values in nested dictionaries.
7- public struct KeyPath {
7+ public struct KeyPath : Hashable {
88 public var segments : [ String ]
99
1010 public var isEmpty : Bool { return segments. isEmpty }
@@ -41,6 +41,18 @@ extension KeyPath: ExpressibleByStringLiteral {
4141 }
4242}
4343
44+ extension KeyPath : CustomStringConvertible {
45+ public var description : String {
46+ return segments. joined ( separator: " . " )
47+ }
48+ }
49+
50+ public extension KeyPath {
51+ static func + ( lhs: KeyPath , rhs: KeyPath ) -> KeyPath {
52+ return KeyPath ( lhs. description + " . " + rhs. description)
53+ }
54+ }
55+
4456public extension Dictionary where Key == String {
4557 subscript( keyPath keyPath: KeyPath ) -> Any ? {
4658 get {
Original file line number Diff line number Diff line change @@ -74,4 +74,22 @@ final class KeyPathTests : XCTestCase {
7474 let keyPath = KeyPath ( path)
7575 XCTAssertEqual ( keyPath. path, path)
7676 }
77+
78+ func test_description_whenSegmentIsEmpty_shouldReturnEmptyString( ) {
79+ XCTAssertEqual ( KeyPath ( " " ) , " " )
80+ }
81+
82+ func test_description_whenSegmentHasOneElement_shouldReturnThatElement( ) {
83+ XCTAssertEqual ( KeyPath ( " element " ) , " element " )
84+ }
85+
86+ func test_description_whenSegmentHasTwoElements_shouldReturnStringSeparatedByPeriod( ) {
87+ XCTAssertEqual ( KeyPath ( " my.name " ) , " my.name " )
88+ }
89+
90+ func test_pathAppending_whenPathIsValid_shouldReturnAppendedPathsUsingPeriod( ) {
91+ let lhs = " this.is.path.start "
92+ let rhs = " this.is.path.end "
93+ XCTAssertEqual ( KeyPath ( lhs) + KeyPath( rhs) , " this.is.path.start.this.is.path.end " )
94+ }
7795}
You can’t perform that action at this time.
0 commit comments