Search code examples
swiftcompiler-errorsfirst-class-functions

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


I experience the following problem trying to create a variable that stores an array of functions:

class MySwiftClass {

    // Compilation Error: '()' is not a subtype of 'MySwiftClass'
    var arrayOfFunctions: [() -> Int] = [myFunction] 

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

Actually this code cannot be compiled with error:

'()' is not a subtype of 'MySwiftClass'

But it works if setup this array in runtime:

class MySwiftClass {
    var arrayOfFunctions: [() -> Int] = [() -> Int]()

    init() {
         arrayOfFunctions = [myFunction]
    }

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

Can anybody explain whether it's a bug of Swift compiler or it's expected behaviour? I don't see any reason for compilation error in the first case, moreover error description is meaningfulness as for me.


Solution

  • It's by design in Swift. A initializer assigned to a property (in your case, arrayOfFunctions) cannot access self before init is run. In your case, it's trying to access self.myFunction. You can only access self safely in the init method.

    Look here https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html at "Safety Check 4".