Create mutable Dictionary with dynamic value/keys in SWIFT

14,530

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)")! }
Share:
14,530
cmii
Author by

cmii

Updated on June 13, 2022

Comments

  • cmii
    cmii almost 2 years

    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.

  • Alexander
    Alexander almost 2 years
    This looks like a perfect candidate for Dictionary.init(uniqueKeysWithValues:)
  • Leo Dabus
    Leo Dabus almost 2 years
    @Alexander I like the reduce(into:) approach/syntax