gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:55:56 25 4
gpt4 key购买 nike

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

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

是否有任何合适的方法来初始化 lazy 实例变量,其值取决于 self 的其他对象类型 instance variables (不只是 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

关于swift - 使用依赖于其他实例变量的值初始化惰性实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39867568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com