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

Asked

Viewed 238 times

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 the Alamofire. I would like to create a View, insert a Label and, in this Label, appear the text of the attribute "text" and in another Label, the name of the attribute "name" and another with the value "reference". What’s the best way to do that?

1 answer

1


You need to cast your Any elements to the type of your element: Try as follows, if Voce has trouble Parsing your dictionary in one conditional, best 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"
}
  • But the bank in question I recover as an API. Is there any difference? And how would it look if there were more than one dictionary within the attribute "informations"?

  • You asked how to access one dictionary inside the other, which I already answered. If you want to know how to convert your data (JSON string - server response) to Dictionary [String: Any], you need to convert Data (String UTF8) to dictionary using NSJSONSerialization Jsonobject from data

  • http://stackoverflow.com/a/39462969/2303865

  • Thanks Leo, I’ll test what happened to me! D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.