给出以下内容:
enum Output {
case typeA, typeB
}
class SomeClass {
var outputFunc: (Int) -> () = methodA // error here
var output: Output = .typeA {
didSet {
if output == .typeA {
outputFunc = methodA
}
else {
outputFunc = methodB
}
}
}
func methodA(val: Int) {/* do something */}
func methodB(val: Int) {/* do something */}
}
didSet
中的所有内容都可以正常编译,但是在声明outputFunc
的地方出现错误:
无法将类型'(SomeClass)->(Int)->()'的值转换为指定类型'(Int)->()'
我不确定如何初始化此属性。我尝试将其更改为self.methodA
,但显然self
尚不存在。如果我将outputFunc
的类型更改为(SomeClass) -> (Int) -> ()
,则该属性会编译,但是didSet
给我相反的错误。
该错误消息可能更具描述性,因为真正的错误确实是您在准备好访问self
之前就尝试访问它,因为outputFunc
是实例属性,而methodA
是实例方法。] >
要解决此问题,您可以简单地使outputFunc
lazy
。
lazy var outputFunc: (Int) -> () = methodA
自从你说