A Dictionary Iteration Trick
· Jan 30, 03:22 PMThe Dictionary.Keys function returns an array of Variants. This is frequently useful for iteration. But usually you need to cast the array elements to do what you want.
dim keys() as Variant = d.Keys
for each key as Variant in keys
try
dim w as Window = key
//more code
catch castError as IllegalCastException
//handle
end try
next
But if you are willing to accept being kicked out of the loop by an IllegalCastException, then the following is currently legal.
try
dim keys() as Variant = d.Keys
for each key as Window in keys
//more code
next
catch oops as IllegalCastException
System.Log System.LogLevelError. "A programmer has screwed up."
end try
If an IllegalCastException or TypeMismatchException is raised, it will be raised from the first line, before the loop body is entered. Thus you cannot catch such an exception and continue with iteration. But it some situations, that is acceptable.
For Dictionaries containing only keys for which Variant.StringValue (IntegerValue, etc.) will succeed, you can do the following.
dim d as new Dictionary
d.Value("Foo") = nil
d.Value(47) = nil
d.Value(true) = nil
dim keys() as Variant = d.Keys
for each key as String in keys
//more code
next
Comment
A Bit of Functional Programming By Example Changing the Current Working Directory in a Console Application
Usually, I know what I put into a Dictionary, so I know what I’ll put out of it. I can’t imagine when one really need to use what you showed in your first code example.
Also, why do you load the array into a separate keys() array? Why not simply write:
for each key as String in d.Keys
You realize that this won’t be evaluated in each iteration, don’t you? Even, it won’t change if you should alter the dictionary inside the loop.
And that’s even a so-so documented behaviour, I remember clarifying this on the mailing list a few years ago.
— Thomas Tempelmann · Jan 30, 06:38 PM · #
Why, I did not realize that the “in” parameter would not be recomputed each iteration. But now that you have pointed it out, it makes sense that it would work that way. I’ll have to add that to the wiki.
As for your first point, there are situations in which you may not be certain as to the contents of the Dictionary. If you want to process the remaining elements of the Dictionary, then you should do the cast inside the loop. The point, as you of course understand, is that it is a good idea to know where the error might happen.
— charles · Jan 31, 10:48 AM · #