Swift:参数类型'[String:ValueType]'不符合预期类型'AnyObject'

时间:2015-11-03 07:44:58

标签: swift generics

我有以下代码尝试将字典转换为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

为什么?

2 个答案:

答案 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