Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Argument type '[String:ValueType]' does not conform to expected type 'AnyObject'

Tags:

generics

swift

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?

like image 843
ubertao Avatar asked Nov 03 '15 07:11

ubertao


2 Answers

Since archivedDataWithRootObject expects AnyObject just cast the dictionary

func dataFromDict<ValueType>(dict: [String:ValueType]) -> NSData {
  return NSKeyedArchiver.archivedDataWithRootObject(dict as! AnyObject)
}
like image 173
vadian Avatar answered Nov 19 '22 13:11

vadian


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
like image 1
Vishnu gondlekar Avatar answered Nov 19 '22 15:11

Vishnu gondlekar