Skip to content

Commit 32ef877

Browse files
committed
Look up and reuse the container when asking for the nested container with the same key in JSONEncoder
1 parent a0272f9 commit 32ef877

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

stdlib/public/Darwin/Foundation/JSONEncoder.swift

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -499,8 +499,9 @@ fileprivate struct _JSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingCon
499499
}
500500

501501
public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
502-
let dictionary = NSMutableDictionary()
503-
self.container[_converted(key).stringValue] = dictionary
502+
let containerKey = _converted(key).stringValue
503+
let dictionary = self.container[containerKey] as? NSMutableDictionary ?? NSMutableDictionary()
504+
self.container[containerKey] = dictionary
504505

505506
self.codingPath.append(key)
506507
defer { self.codingPath.removeLast() }
@@ -510,8 +511,9 @@ fileprivate struct _JSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingCon
510511
}
511512

512513
public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
513-
let array = NSMutableArray()
514-
self.container[_converted(key).stringValue] = array
514+
let containerKey = _converted(key).stringValue
515+
let array = self.container[containerKey] as? NSMutableArray ?? NSMutableArray()
516+
self.container[containerKey] = array
515517

516518
self.codingPath.append(key)
517519
defer { self.codingPath.removeLast() }

0 commit comments

Comments
 (0)