微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift将字典值作为类型

我正在寻找最好的方法如何将此代码设置为一行:

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐