Home > OS >  Looping an AnyHashable Dictionary
Looping an AnyHashable Dictionary

Time:10-05

I am trying to loop the information that I got from a Http response, but I am having trouble accessing the data. this is currently the information I am trying to Loop: enter image description here

I was trying to use a For to access the different elements of the response but cant figure out how to access the elements inside the dictionary, this is the code I am using:

var dictionaryMessage: NSMutableDictionary?
            do {
                if let data = result?.data(using: .utf8) {
                    dictionaryMessage = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSMutableDictionary
                    if(dictionaryMessage?["precios"] != nil){
                        var element = dictionaryMessage?["precios"]
                        for (index, element) in element![0]{
                            print("index"   index   "element:"   element)
                        }
                    }
                }
            } catch {
                //error handling
            }
            

I was hoping to find the correct method to access this data, because at the moment I am getting this error: enter image description here

CodePudding user response:

You can try

var element = dictionaryMessage!["precios"] as! [[String:Any]]

CodePudding user response:

There are a few issues in the code. Swift is a strong typed language, with NS... collection types you get unspecified Any(Object) and you have to conditionally downcast all types.

The value for key precios is an array with String keys and Int values, so the enclosing dictionary dictionaryMessage is [String:[[String:Int]]]

var dictionaryMessage : [String:[[String:Int]]]?
do {
    if let data = result?.data(using: .utf8) {
        dictionaryMessage = try JSONSerialization.jsonObject(with: data) as? [String:[[String:Int]]]
        if let precios = dictionaryMessage?["precios"] {
            for item in precios {
                for (index, element) in item {
                    print("index: \(index) element: \(element)")
                }
            }
        }
    }
} catch {
    print(error)
}

or if there is only one element in the array

do {
    if let data = result?.data(using: .utf8) {
        dictionaryMessage = try JSONSerialization.jsonObject(with: data) as? [String:[[String:Int]]]
        if let precios = dictionaryMessage?["precios"]?.first {
            for (index, element) in precios {
                print("index: \(index) element: \(element)")
            }
        }
    }
} catch {
    print(error)
}
  • Related