在SWIFT中使用动态值/键创建可变字典

cmi*_*mii 2 dictionary nsmutabledictionary ios swift

我需要用动态键创建一个Dictionary.

最后我需要一本词典

我试着用:

var animDictionary:[String:AnyObject]

    for position in 1...10
    {
        let strImageName : String = "anim-\(position)"
        let image  = UIImage(named:strImageName)
        animDictionary.setValue(image, forKey: strImageName) //NOT WORK 
       //BECAUSE IT'S NOT A NSMUTABLEDICTIONARY
    }
Run Code Online (Sandbox Code Playgroud)

所以我尝试过:

var animMutableDictionary=NSMutableDictionary<String,AnyObject>()

    for position in 1...10
    {
        let strImageName : String = "anim-\(position)"
        let image  = UIImage(named:strImageName)
        animMutableDictionary.setValue(image, forKey: strImageName) 
    }
Run Code Online (Sandbox Code Playgroud)

但是我没有找到如何将我的NSMutableDictionary转换为Dictionary.我不确定这是可能的.

在Apple doc中,我发现:

Apple Doc

我不知道在我的情况下是否可以使用它.

Leo*_*bus 8

试试这样:

var animDictionary: [String: Any] = [:]

(1...10).forEach { animDictionary["anim-\($0)"] = UIImage(named: "anim-\($0)")! }
Run Code Online (Sandbox Code Playgroud)