Search code examples
swiftswift3swifty-json

how can I assign an embedded json to a variable in Swift?


My backend code returns the following json:

...
 "_id": "some_id",
 "opening_hours": {
    "mon": "9-5",
    "tue": "9-5",
    "wed": "9-5",
    "thu": "9-5",
    "fri": "9-5",
    "sat": "10-3",
    "sun": "closed"
}
...

and I want to assign the opening_hours to a variable in my Swift app, so that I can easily access different days from there. I'm using SwiftyJSON.

I tried to do it with the following code:

var openingHours:[String:String] = [:]
    if(json["opening_hours"] != nil){
        openingHours = json["opening_hours"].dictionary
    }

but I have an error:

Cannot assign value of type '[String : JSON]?' to type '[String : String]'

How can I make it easily accessible then?


Solution

  • What you are looking for is dictionaryObject property, it will return [String:Any]? object so type cast it to [String:String] will works for you.

    var openingHours:[String:String] = [:]
    if(json["opening_hours"] != nil){
        openingHours = json["opening_hours"].dictionaryObject as? [String:String] ?? [:]
    }