简体   繁体   English

Swift init()中不可变字典类型的Initialize属性

[英]Initialize property of type immutable dictionary in Swift init()

I would like to initialize an immutable dictionary by calculating its values in init() . 我想通过在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. 有什么方法可以使用let而不是var语义来定义此属性。 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".) (如果仅将这个var更改为let我当前在循环内收到此错误,则为该错误:“不变值'self.images'可能未分配给”。)

Make an additional variable in init and assign it once to images : init添加一个附加变量,并将其分配给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
    }
}

If you do not require self during the dictionary computation, another option is to use an initialization block. 如果在字典计算过程中不需要self ,则另一个选择是使用初始化块。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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