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:
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)
}
}