first-class 的数组作为 Swift 中的实例变量

Array of first-class functions as an instance variable in Swift

我在尝试创建存储函数数组的变量时遇到以下问题:

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 在 "Safety Check 4" 查看此处。

正如@tng所说,这是正确的,我想提出一个解决方案,它使用静态方法,如下所示:

class MySwiftClass {


    var arrayOfFunctions: [() -> Int] = [MySwiftClass.myFunction]

    static func myFunction() -> Int {
        return 0
    }
}