我有以下代码尝试将字典转换为NSData:
func dataFromDict<ValueType>(dict: [String:ValueType]) -> NSData {
return NSKeyedArchiver.archivedDataWithRootObject(dict)
}
编译器在传递dict
作为参数时给出了这个错误:
Argument type '[String:ValueType]' does not conform to expected type 'AnyObject'
修改:
@ vadian的解决方案对我有用。
我还尝试将字典转换为NSDictionary
:
return NSKeyedArchiver.archivedDataWithRootObject(dict as NSDictionary)
但是得到了这个错误:
Cannot convert value of type '[String:ValueType]' to type 'NSDictionary' in coercion
为什么?
答案 0 :(得分:4)
由于archivedDataWithRootObject
期望AnyObject
只是投了字典
func dataFromDict<ValueType>(dict: [String:ValueType]) -> NSData {
return NSKeyedArchiver.archivedDataWithRootObject(dict as! AnyObject)
}
答案 1 :(得分:1)
您可以使用NSJSONSerialization将字典转换为NSData。试试这个
let params = ["key1":"1","key2":"0"] as Dictionary<String, AnyObject>
let data = try? NSJSONSerialization.dataWithJSONObject(params, options:NSJSONWritingOptions.PrettyPrinted) as NSData