SetValueForKeys not working Swift

I have the following code in a playground:

class Pokemon : NSObject {

    var name :String!
    var id :Int?
    var imageURL :String!
    var latitude :Double!
    var longitude :Double!

    init(dictionary :[String:Any]) {

        super.init()
        setValuesForKeys(dictionary)
}
}

let dict :[String:Any] = ["name":"John","imageURL":"someimageURL","latitude":45.67]
let pokemon = Pokemon(dictionary: dict)

      

When setValuesForKeys is called, it will throw an exception saying the following:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__lldb_expr_13.Pokemon 0x6000000ffd00> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key latitude.'

      

I have the key "latitude", but for some reason it cannot find it. Any ideas!

+3


source to share


1 answer


The type Double!

(likewise Double?

) has no match in the Objective-C world, so it doesn't appear as an Objective-C property , so Key-Value Coding cannot find a key named "latitude" and fails.

You have to convert these fields to non-optional if you want KVC.



class Pokemon : NSObject {
    var name: String!
    var id: Int = 0
    var imageURL: String!
    var latitude: Double = 0.0
    var longitude: Double = 0.0

    init(dictionary: [String: Any]) {
        super.init()
        setValuesForKeys(dictionary)
    }
}

      

+5


source







All Articles