The code in the minimal example (so minimal it does not really make sense...) below crashes: *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__lldb_expr_345.People 0x60800002a5a0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key names.'
It works just fine if the dictionary is change from [String, LastName?]
to [String, LastName]
. So I guess the type Optional<LastName>
is not representable using KVC some how? I thought it would be able to infer the type to _Nullable
.
How can I make this code work with a dictionary containing Optional values (my own NSObject subclass or value types)?
class LastName: NSObject {
let name: String
init(_ name: String) { self.name = name }
override var description: String { return name }
}
class People: NSObject {
var names: [String: LastName?] = [:] //problem caused by optional `Lastname`
override var description: String {
return "names: \(names)"
}
}
func createPeople(_ names: [String: LastName]) -> NSObject {
let classType: NSObject.Type = People.self
let instance = classType.init()
instance.setValue(names, forKey: "names") //crash here NSUnknownKeyException
return instance
}
print(createPeople(["Steve": LastName("Jobs")]))