我有以下代码尝试将字典转换为NSData:
func dataFromDict<ValueType>(dict: [String:ValueType]) -> NSData {
return NSKeyedArchiver.archivedDataWithRootObject(dict)
}
Run Code Online (Sandbox Code Playgroud)
编译器给我这个错误dict作为参数传递:
Argument type '[String:ValueType]' does not conform to expected type 'AnyObject'
编辑:
@ vadian的解决方案对我有用.
我还试图将这个词组投射到NSDictionary:
return NSKeyedArchiver.archivedDataWithRootObject(dict as NSDictionary)
Run Code Online (Sandbox Code Playgroud)
但是得到这个错误:
Cannot convert value of type '[String:ValueType]' to type 'NSDictionary' in coercion
为什么?
因为archivedDataWithRootObject期望AnyObject只是投射字典
func dataFromDict<ValueType>(dict: [String:ValueType]) -> NSData {
return NSKeyedArchiver.archivedDataWithRootObject(dict as! AnyObject)
}
Run Code Online (Sandbox Code Playgroud)