【发布时间】:2020-05-07 15:37:20
【问题描述】:
鉴于以下情况:
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.methodA,但显然self还不存在。”。确切地!如果你已经明白self此时不存在,那么你应该明白为什么你不能做var outputFunc: (Int) -> () = methodA。methodA和self.methodA是一回事。 -
正如@Sweeper 所说,您还没有
self可用,但如果您愿意在首次使用时对其进行初始化,您可以将其更改为lazy属性。
标签: swift function types properties