Skip to content

Commit

Permalink
#3 Add appending function to KeyPath using the "+" operator
Browse files Browse the repository at this point in the history
  • Loading branch information
rogerluan authored May 28, 2022
2 parents 914d782 + 59039f0 commit 3df9171
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
14 changes: 13 additions & 1 deletion Sources/KeyPath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Foundation

/// Simple struct used to represent multiple segments of a string.
/// This is a utility used to recursively access values in nested dictionaries.
public struct KeyPath {
public struct KeyPath: Hashable {
public var segments: [String]

public var isEmpty: Bool { return segments.isEmpty }
Expand Down Expand Up @@ -41,6 +41,18 @@ extension KeyPath: ExpressibleByStringLiteral {
}
}

extension KeyPath: CustomStringConvertible {
public var description: String {
return segments.joined(separator: ".")
}
}

public extension KeyPath {
static func + (lhs: KeyPath, rhs: KeyPath) -> KeyPath {
return KeyPath(lhs.description + "." + rhs.description)
}
}

public extension Dictionary where Key == String {
subscript(keyPath keyPath: KeyPath) -> Any? {
get {
Expand Down
18 changes: 18 additions & 0 deletions Tests/KeyPathTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,22 @@ final class KeyPathTests : XCTestCase {
let keyPath = KeyPath(path)
XCTAssertEqual(keyPath.path, path)
}

func test_description_whenSegmentIsEmpty_shouldReturnEmptyString() {
XCTAssertEqual(KeyPath(""), "")
}

func test_description_whenSegmentHasOneElement_shouldReturnThatElement() {
XCTAssertEqual(KeyPath("element"), "element")
}

func test_description_whenSegmentHasTwoElements_shouldReturnStringSeparatedByPeriod() {
XCTAssertEqual(KeyPath("my.name"), "my.name")
}

func test_pathAppending_whenPathIsValid_shouldReturnAppendedPathsUsingPeriod() {
let lhs = "this.is.path.start"
let rhs = "this.is.path.end"
XCTAssertEqual(KeyPath(lhs) + KeyPath(rhs), "this.is.path.start.this.is.path.end")
}
}

0 comments on commit 3df9171

Please sign in to comment.