我正在尝试在Swift中进行一个简单的扩展,从而可以轻松地将Dictionary转换为JSON NSData NSJSONSerialization.dataWithJSONObject
。
extension Dictionary {
func toJSONData() -> NSData! {
return NSJSONSerialization.dataWithJSONObject(self, options: nil, error: nil)
}
}
我不太清楚为什么不能编译。它给我一个类型错误:
Cannot downcast from 'Dictionary<Key, Value>' to non-@objc protocol type 'AnyObject'
有任何想法吗?我已经四处搜寻,却找不到任何东西。
我已经对此进行了测试,并且效果很好:
return NSJSONSerialization.dataWithJSONObject(["":""], options: nil, error: nil)
(根据我上面的评论:)问题在于,并非所有Swift字典都可以转换为AnyObject
,只有type可以转换为[NSObject: AnyObject]
。而且,定义仅适用于某些受限泛型类型的泛型类型的扩展似乎是不可能的(数组扩展也有类似的问答)。
您可以使用一个函数(如Nate在他的答案中建议的那样),或者定义一个扩展名NSDictionary
。
Swift 2的更新:从Swift 2开始,您可以定义仅适用于某些受限通用类型的通用类型扩展:
extension Dictionary where Key : NSObject, Value : AnyObject {
func toJSONData() -> NSData! {
return try? NSJSONSerialization.dataWithJSONObject(self, options: [])
}
}
然后
let d1 = ["foo" : "bar"].toJSONData()
可以按预期进行编译和工作,但是
struct Bar {}
let d2 = [ "foo" : Bar() ].toJSONData()
因为Bar()
不是而不编译AnyObject
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句