swift – 使用依赖于其他实例变量的值初始化惰性实例变量

以下初始化当前在调用getEventCalendar的行中生成此错误:

Cannot use instance member ‘getEventCalendar’ within property
initializer; property initializers run before ‘self’ is available.

是否有任何合适的方法来初始化惰性实例变量的值取决于self的其他对象类型实例变量(不仅仅是自我alone)?我已经例如尝试将getEventCalendar从方法转换为函数,但这也无济于事.

class AbstractEventCalendarClient {

  let eventStore: EKEventStore
  let entityType: EKEntityType

  lazy var eventCalendar = getEventCalendar()

  init(eventStore: EKEventStore,entityType: EKEntityType) {
    self.eventStore = eventStore
    self.entityType = entityType
  }

  func getEventCalendar() -> EKCalendar? {
    // ...
  }
}
你可以使用一次只执行的闭包来捕获self的属性并在执行时使用它们(=首先使用lazy属性).例如.
class Foo {
    var foo: Int
    var bar: Int
    lazy var lazyFoobarSum: Int = { return self.foo + self.bar }()

    init(foo: Int,bar: Int) { 
        self.foo = foo 
        self.bar = bar
    }
}

let foo = Foo(foo: 2,bar: 3)
foo.foo = 7
print(foo.lazyFoobarSum) // 10

W.r.t.对于你自己的尝试:你可以以同样的方式在这个曾经执行过的闭包中使用self的帮助(实例)函数.

class Foo {
    var foo: Int
    var bar: Int
    lazy var lazyFoobarSum: Int = { return self.getFooBarSum() }()

    init(foo: Int,bar: Int) { 
        self.foo = foo 
        self.bar = bar
    }

    func getFooBarSum() -> Int { return foo + bar }
}

let foo = Foo(foo: 2,bar: 3)
foo.foo = 7
print(foo.lazyFoobarSum) // 10

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...