Reputation: 93
I'm trying to find a way to initialize a Dictionary inline in ActionScript 3, like:
private var sampleDic:Dictionary = new Dictionary (
{ "zero", "Hello" },
{ "one", "World" }
);
I tried many ways, but none works. Anyone knows if it's possible, and how?
Thanks
Upvotes: 9
Views: 6337
Reputation: 146
If it's static you can do this with a block
private static var myDict:Dictionary = new Dictionary();
{
myDict["zero"] = "Hello";
myDict["one"] = "World";
}
Upvotes: 6
Reputation: 1377
You can extend dictionary class and override default constructor with one that accepts initial key-value pears.
EDIT:
You can also use this dirty JS like solution :)
import flash.utils.Dictionary;
var dict : Dictionary = function ( d : Dictionary, p : Object ) : Dictionary { for ( var i : String in p ) { d[i] = p[i] }; return d; }(new Dictionary(), {
"zero": "Hello",
"one": "World"
})
trace( dict["zero"] );
Upvotes: 2
Reputation: 5204
If you REALLY want something like that, you can use a Dictionary factory:
public class DictFactory
{
public var dict:Dictionary;
public function create(obj:Object):Dictionary
{
dict = new Dictionary();
for (var key:String in obj) {
dict[key] = obj[key];
}
return dict;
}
}
Usage:
private var sampleDic:Dictionary = new DictFactory().create({ "zero":"Hello", "one": "World" });
The DictFactory.create
expects a Object with key-values, that will be applied to the returned Dictionary, if you pass any other object (in AS3, any class is Object), results may be undesireable. :)
Upvotes: 5
Reputation: 13532
If there is no specific reason to use a Dictionary you can do it with an object.
private var sample:Object = {
"zero": "Hello",
"one": "World"
};
Upvotes: 0
Reputation: 58805
No, you can't do it. You have to construct a dictionary and then add the values in a loop or individually.
Upvotes: 8