-1

I would like to initialize an immutable dictionary by calculating its values in init(). I currently have:

class MyClass {
    var images: [String: UIImage]

    func init() {
        images = [:]
        for // ... loop over strings
            // ... calculate image
            images[string] = image
    }
}

Is there any way to define this property with let instead of var semantics. This would be convenient and seem appropriate as its content won't be changed after the object has been initialized. (If I just change this var into let I currently receive this error for the assignment inside the loop: "immutable value 'self.images' may not be assigned to".)

Drux
  • 11,992
  • 13
  • 66
  • 116
  • 1
    Just build the dictionary in a local variable first and then assign to the property ... – Martin R Aug 19 '15 at 13:56
  • It might also be possible to use a functional expression to create the dictionary in one go but you would need to share more information about the calculation for that. – hennes Aug 19 '15 at 18:37

2 Answers2

2

Make an additional variable in init and assign it once to images:

class MyClass {
    let images: [String: UIImage]

    func init() {
        var tempImages = [String: UIImage]()
        for // ... loop over strings
            // ... calculate image
            tempImages[string] = image

        // assign tempImages to images
        images = tempImages
    }
}
Qbyte
  • 12,753
  • 4
  • 41
  • 57
1

If you do not require self during the dictionary computation, another option is to use an initialization block.

class MyClass {

    let images: [String: UIImage] = {
        var images = [String: UIImage]()
        images["foo"] = UIImage(named: "foo")
        images["bar"] = UIImage(named: "bar")
        return images
    }()

    // no explicit init required

}
hennes
  • 9,147
  • 4
  • 43
  • 63