I have following code trying to convert a dictionary to NSData:
func dataFromDict<ValueType>(dict: [String:ValueType]) -> NSData {
return NSKeyedArchiver.archivedDataWithRootObject(dict)
}
The compiler gives me this error for passing dict
as argument:
Argument type '[String:ValueType]' does not conform to expected type 'AnyObject'
Edit:
@vadian's solution worked for me.
I also tried to cast the dict to NSDictionary
:
return NSKeyedArchiver.archivedDataWithRootObject(dict as NSDictionary)
But getting this error:
Cannot convert value of type '[String:ValueType]' to type 'NSDictionary' in coercion
Why?
Since archivedDataWithRootObject
expects AnyObject
just cast the dictionary
func dataFromDict<ValueType>(dict: [String:ValueType]) -> NSData {
return NSKeyedArchiver.archivedDataWithRootObject(dict as! AnyObject)
}
You can use NSJSONSerialization to convert dictionary into NSData. Try this
let params = ["key1":"1","key2":"0"] as Dictionary<String, AnyObject>
let data = try? NSJSONSerialization.dataWithJSONObject(params, options:NSJSONWritingOptions.PrettyPrinted) as NSData
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With