我在尝试创建存储函数数组的变量时遇到以下问题:
class MySwiftClass {
// Compilation Error: '()' is not a subtype of 'MySwiftClass'
var arrayOfFunctions: [() -> Int] = [myFunction]
func myFunction() -> Int {
return 0
}
}
实际上这段代码不能编译错误:
'()' is not a subtype of 'MySwiftClass'
但如果在运行时设置这个数组,它会起作用:
class MySwiftClass {
var arrayOfFunctions: [() -> Int] = [() -> Int]()
init() {
arrayOfFunctions = [myFunction]
}
func myFunction() -> Int {
return 0
}
}
谁能解释这是 Swift 编译器的错误还是预期的行为?在第一种情况下,我没有看到编译错误的任何原因,而且错误描述对我来说是有意义的。
请您参考如下方法:
这是在 Swift 中设计的。在运行 init 之前,分配给属性(在您的情况下为 arrayOfFunctions)的初始化器无法访问 self。在您的例子中,它正在尝试访问 self.myFunction。您只能在 init 方法中安全地访问 self。
看这里https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html在“安全检查 4”处。
