给定以下内容:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句