Skip to content

Commit 88b4575

Browse files
committed
Fix Generation of Sub-Keys in Dictionaries
The tool was previously non-deterministic in code generation for different orders of property lists passed as parameters. This generated some side effects where blocks of code wouldn’t be generated at all depending on the order of property lists that were passed to the tool **and** the difference in keys between these property lists. This commit introduces a smarter behavior for property lists that contain dictionaries, and these dictionaries contain different keys, also called sub-keys in this context. Before code generation already known keys that aren’t present in the currently processed property list are merged with its contents, so that further code generation methods can determine the optionality of these keys. These keys were previously not part of the generated code.
1 parent a527e77 commit 88b4575

1 file changed

Lines changed: 22 additions & 13 deletions

File tree

Plist2swift/Plist2swift.swift

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -620,22 +620,31 @@ for plistPath in plists {
620620
}
621621

622622
for key in allKeys {
623-
if (keysAndTypes[key] == nil) {
624-
let type = typeForValue(tuples[key]!)
625-
keysAndTypes[key] = type
626-
// Generate protocols for Dictionary entries
627-
if (type == "Dictionary<String, Any>") {
623+
guard let tuple = tuples[key] else {
624+
continue
625+
}
628626

629-
let dictionary = tuples[key] as? Dictionary<String, Any>
630-
let sortedDictionary = dictionary?.sorted { (pairOne, pairTwo) -> Bool in
631-
return pairOne.key < pairTwo.key
627+
let type = typeForValue(tuple)
628+
if (type != "Dictionary<String, Any>") { // Just register the existence of primitive types
629+
keysAndTypes[key] = type
630+
} else { // Generate protocols for Dictionary entries
631+
var dictionary = tuples[key] as? Dictionary<String, Any> ?? [:]
632+
633+
// Merge sub-keys in dictionaries from current property list with already known sub-keys from dictionaries
634+
// with the same name.
635+
if let keyValueTuples = allKeyValueTuples[key] {
636+
for knownKey in Set<String>(keyValueTuples.keys).subtracting(Set(dictionary.keys)) {
637+
for (tupleKey, tupleValue) in keyValueTuples.tuples {
638+
if (tupleKey == knownKey) {
639+
dictionary[tupleKey] = tupleValue
640+
}
641+
}
632642
}
633-
634-
allKeyValueTuples[key] = KeyValueTuples(tuples: sortedDictionary ?? [])
635-
let name = key.uppercaseFirst()
636-
let protocolName = name.appending("Protocol")
637-
keysAndTypes[key] = protocolName
638643
}
644+
645+
allKeyValueTuples[key] = KeyValueTuples(tuples: dictionary.sorted { $0.key < $1.key })
646+
// Generate protocol name
647+
keysAndTypes[key] = key.uppercaseFirst().appending("Protocol")
639648
}
640649
}
641650

0 commit comments

Comments
 (0)