Swift: The argument type '[String: ValueType]' does not match the expected type 'AnyObject'

I have the following code that is trying to convert a dictionary to NSData:

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

The compiler gives me this error to pass the dict as an argument:

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

Edit

Decision

@vadian worked for me.

I also tried applying a dict to an NSDictionary :

 return NSKeyedArchiver.archivedDataWithRootObject(dict as NSDictionary) 

But getting this error:

Cannot convert value of type '[String:ValueType]' to type 'NSDictionary' in coercion

Why?

+5
source share
2 answers

Since archivedDataWithRootObject expects AnyObject , just enter the dictionary

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

You can use NSJSONSerialization to convert a dictionary to NSData. try it

 let params = ["key1":"1","key2":"0"] as Dictionary<String, AnyObject> let data = try? NSJSONSerialization.dataWithJSONObject(params, options:NSJSONWritingOptions.PrettyPrinted) as NSData 
+1
source

Source: https://habr.com/ru/post/1235088/


All Articles