问题描述
以下初始化当前在调用 getEventCalendar
的行中产生此错误:
The following initialization currently produces this error in the line that calls getEventCalendar
:
不能在属性中使用实例成员getEventCalendar"初始化程序;属性初始值设定项在 'self' 可用之前运行.
是否有任何合适的方法可以使用依赖于 self
的其他对象类型 instance variables
的值来初始化 lazy
实例变量(不只是 self
单独)?我已经例如尝试将 getEventCalendar
从方法转换为函数,但这也无济于事.
Is there any suitable way for initializing the lazy
instance variable with a value that depends on other object-type instance variables
of self
(not just self
alone) ? I've e.g. tried turning getEventCalendar
from a method into a function, but this does not help either.
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
的属性并在执行时使用这些(= 第一次使用 属性).例如
You can use a once-only executed closure which captures properties of self
and use these at execution (= first use of the lazy
property). E.g.
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
的帮助(实例)函数.
W.r.t. to your own attempt: you may, in the same way, make use of help (instance) functions of self
in this once-only executed closure.
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
这篇关于使用依赖于其他实例变量的值初始化惰性实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!