Search code examples
swiftxcodeanyobject

Why I am getting 'valueForUndefinedKey' error when using AnyObject in Swift?


Im have a question. Why the following crash reason? since "name" exists?

viewcontroller1:


struct pointDict {
    let id: Int
    let name: String
}
var pointsPlane: [pointDict] = []

let wp = pointDict(id: 123, name: "test")
pointsPlane.append(wp)

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {


if let destVC = segue.destination as? viewcontroller2 {
destVC.dt = pointsPlane[0] as AnyObject

}
}

viewcontroller2:

var dt: AnyObject?
let detail = self.dt
name.text = detail?.value(forKeyPath: "name") as? String

Crash Report:

valueForUndefinedKey:]: this class is not key value coding-compliant for the key name


Solution

  • AnyObject is reference type but a struct is value type and therefore is not ObjC key-value coding compliant.

    Your approach is bad practice anyway. A swiftier way is to declare the properties with the real type. The default declaration of detail in the template is not needed.

    viewcontroller1:

    struct PointDict {
        let id: Int
        let name: String
    }
    var pointsPlane: [PointDict] = []
    
    let wp = PointDict(id: 123, name: "test")
    pointsPlane.append(wp)
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) 
        if let destVC = segue.destination as? viewcontroller2 {
            destVC.dt = pointsPlane.first
        }
    }
    

    viewcontroller2:

    var dt : PointDict? 
    
    override func viewDidLoad() {
        super.viewDidLoad()
        name.text = dt?.name ?? ""
    }