加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift将字典值作为类型

发布时间:2020-12-14 04:57:33 所属栏目:百科 来源:网络整理
导读:我正在寻找最好的方法如何将此代码设置为一行: if (dictionary["Amoumt"] is Double) { amount = dictionary["Amount"] as Double} else { amount = NSString(string: dictionary["Amount"] as String).doubleValue} 我有Dictionary String,AnyObject我想解
我正在寻找最好的方法如何将此代码设置为一行:

if (dictionary["Amoumt"] is Double) {
    amount = dictionary["Amount"] as Double
} else {
    amount = NSString(string: dictionary["Amount"] as String).doubleValue
}

我有Dictionary< String,AnyObject>我想解析它的价值.我正在使用上面的代码但它的行太多了.我想把它变成一条线.就像是:

dictionary["Amount"].parseDouble()

使用此方法创建扩展没有问题:

func parseDouble() -> Double {
    if (self is Double) {
        return self as Double
    } else {
        return NSString(string:(self as String)).doubleValue
    }
}

但是我应该扩展哪种类型?接下来你能用通用方法帮我吗?所以我可以这样打电话:

dictionary["Amount"].parse(Double)

这是如何做到这一点的好方法还是我应该采取另一种方式?

解决方法

您可以按原样使用AnyObject.尝试:

var dictionary:[String:AnyObject] = [
    "foo": 4.21,// NSNumber
    "bar": "42.5",// NSString
    "baz": [1,2,3],// NSArray
]

let foo = dictionary["foo"]?.doubleValue ?? 0 // -> 4.21
let bar = dictionary["bar"]?.doubleValue ?? 0 // -> 42.5
let baz = dictionary["baz"]?.doubleValue ?? 0 // -> 0.0

这是有效的,因为NSNumber和NSString都具有.doubleValue属性.
另一方面,NSArray没有该属性,在这种情况下它返回nil.

如the document中所述:

You can also call any Objective-C method and access any property without casting to a more specific class type. This includes Objective-C compatible methods marked with the @objc attribute.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读