Skip to content

Commit 3df9171

Browse files
authored
#3 Add appending function to KeyPath using the "+" operator
2 parents 914d782 + 59039f0 commit 3df9171

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

Sources/KeyPath.swift

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff 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+
4456
public extension Dictionary where Key == String {
4557
subscript(keyPath keyPath: KeyPath) -> Any? {
4658
get {

Tests/KeyPathTests.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)