Andrius Steponavičius Andrius Steponavičius - 5 months ago 55
Swift Question

extension of Dictionary where <String, AnyObject>

I am trying to create dictionary extension where Dictionary is of a certain type

Was looking in many places and trying different aproaches, none of them seem to work, this was one of them

extension Dictionary where <String, AnyObject>{
var jsonString:String {
return ""
}
}


Another method that didnt actualy worked for some reason

extension Dictionary where Key:Hashable, Value:AnyObject {

var jsonString:String {

do {
let stringData = try NSJSONSerialization.dataWithJSONObject(self, options: NSJSONWritingOptions.PrettyPrinted)
if let string = String(data: stringData, encoding: NSUTF8StringEncoding){
return string
}
}catch _ {

}
return ""
}
}


Argument type 'Dictionary' does not conform to expected type of 'AnyObject'

Answer

Do this:

extension Dictionary where Key: StringLiteralConvertible, Value: AnyObject {
    var jsonString: String {
        return ""
    }
}

As per your updated answer. Json serialization needs an object, Swift Dictionaries are structs. You need to convert to an NSDictionary You must specify Key to conform to NSObject to properly convert to an NSDictionary.

Small note: Dictionaries already type constrain Key to be Hashable, so your original constraint wasn't adding anything.

extension Dictionary where Key: NSObject, Value:AnyObject {

    var jsonString:String {

        do {
            let stringData = try NSJSONSerialization.dataWithJSONObject(self as NSDictionary, options: NSJSONWritingOptions.PrettyPrinted)
            if let string = String(data: stringData, encoding: NSUTF8StringEncoding){
                return string
            }
        }catch _ {

        }
        return ""
    }
}

Note, that the dictionaries must conform to this type to access the extension.

let dict = ["k" : "v"]

Will become type [String : String], so you must be explicit in declaring:

let dict: [NSObject : AnyObject] = ["k" : "v"]