From 81e905aa7df68e7326e9bfece7a50b89cc992d75 Mon Sep 17 00:00:00 2001 From: Roger Oba Date: Wed, 1 Jun 2022 22:10:22 -0300 Subject: [PATCH] Fix issue when writing to empty dictionary. --- Sources/KeyPath.swift | 2 +- Tests/KeyPathTests.swift | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Sources/KeyPath.swift b/Sources/KeyPath.swift index 1208aad..b15b42e 100644 --- a/Sources/KeyPath.swift +++ b/Sources/KeyPath.swift @@ -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 diff --git a/Tests/KeyPathTests.swift b/Tests/KeyPathTests.swift index b5ab53b..fa69153 100644 --- a/Tests/KeyPathTests.swift +++ b/Tests/KeyPathTests.swift @@ -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) + } }