簡體   English   中英

Swift init()中不可變字典類型的Initialize屬性

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

我想通過在init()計算其值來初始化不可變字典。 我目前有:

class MyClass {
    var images: [String: UIImage]

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

有什么方法可以使用let而不是var語義來定義此屬性。 這將很方便,而且似乎很適當,因為在初始化對象后不會更改其內容。 (如果僅將這個var更改為let我當前在循環內收到此錯誤,則為該錯誤:“不變值'self.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
    }
}

如果在字典計算過程中不需要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