ubertao
ubertao

Reputation: 229

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

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?

Upvotes: 5

Views: 13294

Answers (2)

vadian
vadian

Reputation: 285074

Since archivedDataWithRootObject expects AnyObject just cast the dictionary

func dataFromDict<ValueType>(dict: [String:ValueType]) -> NSData {
  return NSKeyedArchiver.archivedDataWithRootObject(dict as! AnyObject)
}

Upvotes: 4

Vishnu gondlekar
Vishnu gondlekar

Reputation: 3956

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

Upvotes: 1

Related Questions