0

I am trying to extend Dictionary with the following code:

extension Dictionary where Key: ExpressibleByStringLiteral, Value: AnyObject {

    var jsonString: String? {
    if let dict = (self as AnyObject) as? Dictionary<String, AnyObject> {
        do {
            let data = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions(rawValue: UInt.allZeros))
            if let string = String(data: data, encoding: String.Encoding.utf8) {
                return string
            }
        } catch {
            print(error)
        }
    }
    return nil
    }

}

Where I write something like:

let x: [String: String] = ["": ""]    
x.jsonString

I get this error:

Value of type '[String: String]' as no member 'jsonString'

Anything I am missing?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
bashan
  • 3,572
  • 6
  • 41
  • 58

2 Answers2

3

There is no need to constrain Dictionary Value type at all:

extension Dictionary where Key: ExpressibleByStringLiteral {
    var jsonString: String? {
        guard let data = try? JSONSerialization.data(withJSONObject: self)
        else { return nil }
        return String(data: data, encoding: .utf8)
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Sorry, it doesn't work. Maybe it is related with Swift 4? – bashan Aug 03 '18 at 17:23
  • Doesn’t work it is too vague. I have tested it here with a dictionary [String:String] and it work as expected – Leo Dabus Aug 03 '18 at 18:11
  • Same error... not sure why I keep getting it... Maybe the file of the extension is somehow not recognized...? – bashan Aug 03 '18 at 20:12
  • Make sure your file is listed in the Compile Sources in your app targets build phases – Leo Dabus Aug 03 '18 at 20:15
  • The file is listed in Compile Sources, but it kept not working, so I copied the extension to another file with another working extension and it works. Strange thing... THANKS! – bashan Aug 04 '18 at 08:50
2

Since String is a value type , look for it's

public struct String {

and AnyObject refers to any instance of a class only , and is equivalent to id in Objective-C , so this declaration of x

[String: String] doesn't fit with [String: AnyObject]

because Any refers to any instance of a class, struct, or enum so it'll fit perfectly

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87