Skip to content

Commit 81e905a

Browse files
committed
Fix issue when writing to empty dictionary.
1 parent 3df9171 commit 81e905a

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

Sources/KeyPath.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ public extension Dictionary where Key == String {
8686
// Reached the end of the key path.
8787
self[head] = newValue as? Value
8888
case let (head, remainingKeyPath)?:
89-
let value = self[head]
89+
let value: Any = self[head] ?? [:]
9090
if var nestedDictionary = value as? [Key:Any] {
9191
// Key path has a tail we need to traverse
9292
nestedDictionary[keyPath: remainingKeyPath] = newValue

Tests/KeyPathTests.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,4 +92,11 @@ final class KeyPathTests : XCTestCase {
9292
let rhs = "this.is.path.end"
9393
XCTAssertEqual(KeyPath(lhs) + KeyPath(rhs), "this.is.path.start.this.is.path.end")
9494
}
95+
96+
func test_writingToEmptyDictionary() throws {
97+
let data = "this is my data"
98+
var dictionary: [String:Any] = [:]
99+
dictionary[keyPath: "nested.data"] = data
100+
XCTAssertEqual(dictionary[keyPath: "nested.data"] as? String, data)
101+
}
95102
}

0 commit comments

Comments
 (0)