Use Function in Initializer - Swift?

Viewed 4600

Assume the following:

class A {
    let x : Int
    init() {
        self.x = assign(1)
    }
    func assign(y : Int) -> Int {
        return y
    }
}

This produces an error.

Here is my question : is there a way to call functions within the class initializer?

EDIT: Added error message:

use of 'self' in method call 'assign' before all stored properties are initialized

4 Answers

One other (possibly helpful) option is to have the function you call within the initializer scope:

class A {
    let x : Int
    init() {
        func assign(y : Int) -> Int {
            return y
        }
        self.x = assign(y: 1)
    }
}

I'm doing that in a project right now. I have a large initializer (its actually a parser) and use an initializer-scoped function for error reporting. Of course, I'd prefer the function to be at class scope so I can reuse it between initializers. But at least I can reuse it within each initializer.

Related