Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :

Apple Doc

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

like image 580
cmii Avatar asked Oct 26 '25 07:10

cmii


1 Answers

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)")!
}
like image 81
Leo Dabus Avatar answered Oct 29 '25 00:10

Leo Dabus