1

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.

2 Answers 2

3

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".

Sign up to request clarification or add additional context in comments.

Comments

0

As @tng stated, that is correct, and I would like to propose a solution, which is using a static method, like this:

class MySwiftClass {


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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.