Swift 初始化惰性值

Swift initializing lazy value

我有class

struct Word {
  let text : String
  let added: Date
  let willShow: Date
  let folder: Phase
  let bestTranslation: String
  let translationsProvider: ()->[String]
  lazy var allTranslations : [String] = {self.translationsProvider()}()
}

和初始化器

extension Word {
    init(_ definition: Definition, context translationProvider: 
                                               @escaping ()->[String]){
    self.text = definition.text!
    self.added = definition.added!
    self.willShow = definition.willShow!
    self.folder = Phase(rawValue: definition.folder)!
    self.bestTranslation = definition.best?.text ?? ""
    self.translationsProvider = translationProvider
    }
}

我遇到错误

Return from initializer without initializing all stored properties

有描述

  1. 'self.allTranslations.storage' not initialized

我该如何解决?

我想知道这是否可能是编译器错误。我没有看到你遇到的相同错误,但这会造成 Swift 编译器分段错误 11:

struct Test {
  let foo: String
  lazy var bar: String = { return "" }()
}

extension Test {
  init(_ foo: String) {
    self.foo = foo
  }
}