简体   繁体   English

如何将不可变的Swift属性初始化为计算值?

[英]How do I initialize an immutable Swift property to a computed value ?

When I have this initializer: 当我有这个初始化器时:

let channels : [TVChannel]

required init?(json : NSObject)
{
    if let x = json as? [NSObject]
    {
        self.channels = x.map { TVChannel(json:$0)! }
    }
}

The compiler gives me the error: 编译器给我错误:

Error:(12, 14) constant 'self.channels' used before being initialized 错误:初始化之前使用的(12,14)常量'self.channels'

Why is this ? 为什么是这样 ? And how do I initialize the property my mapped array of TVChannel ? 以及如何初始化我的TVChannel映射数组的TVChannel

The compiler needs to know how to initialize self.channels when the control flow doesn't enter the if let condition. 当控制流未输入if let条件时,编译器需要知道如何初始化self.channels

A solution could be to provide an else branch: 一个解决方案可能是提供else分支:

if let x = json as? [NSObject] {
    self.channels = x.map { TVChannel(json:$0)! }
} else {
    self.channels = []
}

You need to handle both cases where json is and isn't an array of NSObjects. 您需要处理json是和不是NSObjects数组的两种情况。 Alternatively you could define a default value to the property and make it a var 或者,您可以为属性定义默认值并将其设置为var

eg 例如

required init?(json : NSObject) {

  if let x = json as? [NSObject] {
    channels = x.map { TVChannel(json: $0) }
  } else {
    channels = [ ]
  }

}

or 要么

var channels: [TVChannel] = [ ]

or 要么

var channels = [TVChannel]()

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

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