Brandon Bradley
Brandon Bradley

Reputation: 3398

Use Function in Initializer - Swift?

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

Upvotes: 6

Views: 6185

Answers (4)

Darrell Root
Darrell Root

Reputation: 844

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.

Upvotes: 4

szym
szym

Reputation: 5846

You can't call instance methods until the instance is initialized (before init is done), but you can use module-level functions and type methods defined using the class or static keyword.

func compute(y: Int) -> Int {
  return y
}

class A {
  let x: Int

  static func assign(y: Int) -> Int {
    return y
  }

  init () {
    x = A.assign(3) + compute(4)
  }
}

Upvotes: 3

Jelly
Jelly

Reputation: 4532

You could use somethings like:

class A {
    var x : Int!
    init() {
        x = assign(1)
    }
    func assign(y : Int) -> Int {
        return y
    }
}

The downside of this approach is that you will get a runtime error if you access x and it is not initialised. Check out this answer.

Upvotes: 0

Oleg Gordiichuk
Oleg Gordiichuk

Reputation: 15512

I think it is not the greatest solution but still it is working.

 class A {
        var variable : Int

        init() {

            self.variable = A.assign(1)

        }

        private class func assign(y : Int) -> Int {
            return y
        }
    }

Upvotes: 2

Related Questions