我有下面的代码试图字典转换为NSData的:斯威夫特:参数类型“[字符串:值类型]”不符合预期的类型“AnyObject”
func dataFromDict<ValueType>(dict: [String:ValueType]) -> NSData {
return NSKeyedArchiver.archivedDataWithRootObject(dict)
}
编译器给了我这个错误传递dict
作为参数:
Argument type '[String:ValueType]' does not conform to expected type 'AnyObject'
编辑:
@v adian的解决方案为我工作。
我也试着投词典到NSDictionary
:
return NSKeyedArchiver.archivedDataWithRootObject(dict as NSDictionary)
但收到此错误:
Cannot convert value of type '[String:ValueType]' to type 'NSDictionary' in coercion
为什么?
不要扔掉类型信息。希望您可以将输入字典值限制为实际类型,以便以后知道如何解码它们。是的,你可以使用强制转换消除/忽略编译器警告,但它仍然不能解决实际问题。 –