0
votes

I'm doing the same operation again and again, namely converting a dictionary to JSON and NSData. Using Dan Kogai's JSON class https://github.com/dankogai/swift-json, I want to create an extension as follows:

extension Dictionary {
   func toDataJSON() -> NSData? {

       return JSON(self as Dictionary<String, AnyObject>)
                   .toString(pretty: false)
                   .dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
   }
}

I realize that not all Dictionary<key, value> sets are compatible with JSON, but for the sensible combination like Dictionary<String, AnyObject>I would like the above to work.

The compiler says:

'Key' is not identical to 'String'

Without casting self to Dictionary<String, AnyObject> it says:

Type 'Dictionary' does not conform to protocol 'AnyObject'

Any insights?

1

1 Answers

0
votes

Since Dictionary is a template class, and since you can't extend specific variants of a template class (you want extension Dictionary<String, AnyObject>, you won't be able to do this like you want. Your best bet is probably a global function:

func toDataJSON(dict:Dictionary<String, AnyObject>) -> NSData? {
    ...
}

Something else which might make things more legible is to create a typealias:

typealias JSONObject = Dictionary<String, AnyObject>