How to pass a value from a dictionary (which is inside another dictionary) to a Label? Swift 3 [closed]

1

I have a database something like this:

{
  "status": "OK",
  "data": [
    {
      "id": 1,
      "name": "Mike",
      "informations": [
        {
          "id": 474,
          "text": "My son",
          "reference": "www.google.com",
        }
      ]
    }

I'm looking for this data through Alamofire. I would like to create a View, insert a Label and, in this Label, the text of the "text" attribute appears and in another Label, the name of the "name" attribute and another with the value "reference". What is the best way to do this?

    
asked by anonymous 31.01.2017 / 01:30

1 answer

1

You need to cast your elements from Any to the type of your element: Try it this way, if you have problem parsing your dictionary in a single conditional, better break-down the code below:

let dict: [String: Any] = ["status": "OK", "data": [["id": 1, "name": "Mike", "informations": [[ "id": 474, "text": "My son", "reference": "www.google.com" ]]]]]

if let status = dict["status"] as? String, status == "OK",
    let data = dict["data"] as? [[String: Any]],
    let dataDict = data.first,
    let id = dataDict["id"] as? Int,
    let name = dataDict["name"] as? String,
    let info = dataDict["informations"] as? [[String: Any]],
    let infoDict = info.first,
    let infoID = infoDict["id"] as? Int,
    let text = infoDict["text"] as? String,
    let reference = infoDict["reference"] as? String {
    print(id)     // ""1\n"
    print(name)   // "Mike\n"
    print(infoID) // "474\n"
    print(text)   // "My son\n"
}
    
31.01.2017 / 09:07