Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Looping through Arrays in Dictionaries

Typical noob disclaimer goes here 😉 I am trying to nest an array in a Swift dictionary similar to how you would with JSON. My nested array ("blocks" in the code below) has mixed datatypes in it. When I run my For-in loop on it, I get the error For-in loop requires ‘Any’ to conform to ‘Sequence’ which sounds like it’s helpful – but I’m not sure what to do here. Would love some advice.

My dict:

let levelOneData = [
    "goal": 180,
    "gravity": CGVector(dx: 0.0, dy: -4.0),
    "bombs": 12,
    "blocks": [
        0: [
            "blockSize": "Small",
            "blockPosition": [0, 80],
            "blockIsLocked": false
        ] as [String : Any],
        1: [
            "blockSize": "Medium",
            "blockPosition": [0, 0],
            "blockIsLocked": false
        ] as [String : Any],
    ]
] as [String : Any]

My For loop:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for (index, block) in levelOneData["blocks"]! { <<<< error here
    print(block) 
}

>Solution :

Because the semicyclic form of levelOneData["blocks"]! is Any type, you must explicitly declare the type for use in a repeating statement such as for-in.

Referring to the content of levelOneData at the top, it seems appropriate to use [Int: [String: Any]] as the type casting.
Please refer to the example code below.

    func printData() {
        if let data = levelOneData["blocks"] as? [Int: [String: Any]] {
            for (index, block) in data {
                print(block)
            }
        }
    }

or

    func printData() {
        guard let data = levelOneData["blocks"] as? [Int: [String: Any]] else {
            return
        }
        
        for (index, block) in data {
            print(block)
        }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading