Haxe iteration on Dynamic
Asked Answered
C

2

5

I have a variable of type Dynamic and I know for sure one of its fields, lets call it a, actually is an array. But when I'm writing

var d : Dynamic = getDynamic();
for (t in d.a) {
}

I get a compilation error on line two:

You can't iterate on a Dynamic value, please specify Iterator or Iterable

How can I make this compilable?

Chiccory answered 9/9, 2008 at 12:51 Comment(0)
G
6

Haxe can't iterate over Dynamic variables (as the compiler says).

You can make it work in several ways, where this one is probably easiest (depending on your situation):

var d : {a:Array<Dynamic>} = getDynamic();
for (t in d.a) { ... }

You could also change Dynamic to the type of the contents of the array.

Graycegrayheaded answered 9/9, 2008 at 13:0 Comment(1)
Is it possible to use multiple types an an Array<Dynamic>, such as [0, "Second element", ["Nested array here!"], "another string"]?Gasperoni
B
3

Another way to do the same is to use an extra temp variable and explicit typing:

var d = getDynamic();
var a: Array<Dynamic> = d.a;
for (t in a) { ... }
Bullins answered 15/9, 2008 at 21:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.