Swift:“这个类不符合关键值编码......”对于Double值 [英] Swift: "This class is not key value coding-compliant..." for Double values

查看:81
本文介绍了Swift:“这个类不符合关键值编码......”对于Double值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,我在Swift中有一个简单的数据对象,包含多个属性变量。它们是 String? Double?值类型的混合。我正在尝试使用 valueForKey 检索每个属性的值。我的代码看起来像这样......

I have a scenario in which I have a simple data object in Swift, containing multiple property variables. They are a mix of String? and Double? value types. I'm trying to retrieve the values for each property using valueForKey. My code looks something like this...

let myDataObj = ...
let stringKeyName = "myStringProperty"
let doubleKeyName = "myDoubleProperty"

guard let stringPropertyValue = myDataObj.valueForKey(stringKeyName) else {
    return
}
guard let doublePropertyValue = myDataObj.valueForKey(doubleKeyName) else {
    return
}

第一次获得 stringPropertyValue 工作正常,我能够按预期检索值。但是,检索 doublePropertyValue 的第二次调用失败,并出现例外情况,此类不符合键值myDoubleProperty的键值编码。 / code>

The first call to get stringPropertyValue works fine, and I am able to retrieve the value as expected. However, the second call to retrieve doublePropertyValue fails with an exception saying, "this class is not key value coding-compliant for the key myDoubleProperty.'"

我知道属性名称是正确的,我也知道为此属性设置了一个值。为什么 valueForKey 适用于 String 对象,但不适用于 Double 对象?

I know that the property name is correct, and I also know that a value is set for this property. Why is it that valueForKey works on String objects, but not Double objects?

推荐答案

正确,您只能对可以在Objective-C中表示的类型进行键值编码。不幸的是,在Objective-C中表示为原始数据类型的那些类型(例如Swift的 Int Double 表示为分别在Objective-C中的NSInteger double 如果是选项,则不能这样表示。在Objective-C中,选项只对类类有意义,而不是基本数据类型。

Correct, you can only do key value coding for types that can be represented in Objective-C. Unfortunately, those types that are represented as primitive data types in Objective-C (e.g. Swift's Int and Double are represented as NSInteger and double in Objective-C, respectively) can not be presented as such if they are optionals. In Objective-C, optionals only make sense with class types, not fundamental data types.

这篇关于Swift:“这个类不符合关键值编码......”对于Double值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆