简体   繁体   中英

Create mutable Dictionary with dynamic value/keys in SWIFT

I need to create a Dictionary with dynamic keys.

At the end I need a Dictionary

I tried to use:

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
    }

So I tried:

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

But I don't find the how to convert my NSMutableDictionary to a Dictionary. I'm not sure it's possible.

In the Apple doc, I found :

苹果文档

I don't know if it's possible to use it in my case.

Xcode 11 • Swift 5.1

You need to initialize your dictionary before adding values to it:

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

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

Another option is to use reduce(into:) which would result in [String: UIImage] :

let animDictionary = (1...10).reduce(into: [:]) {
    $0["anim-\($1)"] = UIImage(named: "anim-\($1)")!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM