为什么在 Swift 中使用 AnyObject 时出现 'valueForUndefinedKey' 错误?

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

我有一个问题。为什么会出现以下崩溃原因?因为“名称”存在?

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

崩溃报告:

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

AnyObject 是引用类型,但结构是值类型,因此不符合 ObjC 键值编码。

无论如何,您的方法是不好的做法。 swiftier 方法是用真实类型声明属性。不需要在模板中默认声明detail

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 ?? ""
}