[英]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.