Skip to content

Commit

Permalink
#4 Fix Issue When Writing to Empty Dictionary
Browse files Browse the repository at this point in the history
  • Loading branch information
rogerluan authored Jun 2, 2022
2 parents 3df9171 + 81e905a commit dd73b21
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Sources/KeyPath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public extension Dictionary where Key == String {
// Reached the end of the key path.
self[head] = newValue as? Value
case let (head, remainingKeyPath)?:
let value = self[head]
let value: Any = self[head] ?? [:]
if var nestedDictionary = value as? [Key:Any] {
// Key path has a tail we need to traverse
nestedDictionary[keyPath: remainingKeyPath] = newValue
Expand Down
7 changes: 7 additions & 0 deletions Tests/KeyPathTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,11 @@ final class KeyPathTests : XCTestCase {
let rhs = "this.is.path.end"
XCTAssertEqual(KeyPath(lhs) + KeyPath(rhs), "this.is.path.start.this.is.path.end")
}

func test_writingToEmptyDictionary() throws {
let data = "this is my data"
var dictionary: [String:Any] = [:]
dictionary[keyPath: "nested.data"] = data
XCTAssertEqual(dictionary[keyPath: "nested.data"] as? String, data)
}
}

0 comments on commit dd73b21

Please sign in to comment.