Rasto
Rasto

Reputation: 17844

How to initialize let property of closure type to pointer to some method?

Have a look on following code

class Example {
    let action: String -> ()

    init() {
        action = method //error: Variable self.action used before initialized
    }

    func method(s: String) {
        println(s)
    }
}

I am setting property of closure type to a class method. To reference class method I need to have the single properties initialized but to have it properly inicialized I need to reference that method. How do I get out of the cycle?

I know I can do something like

init() {
    action = {_ in }
    action = method //error: Variable self.action used before initialized
}

but that just is not nice.

The actual thing I need to do is more complex and makes much more sense bt this is the essence.

Upvotes: 5

Views: 2391

Answers (2)

GoZoner
GoZoner

Reputation: 70245

Use a lazy var as such:

enter image description here

The first time you access action the expression self.method will be evaluated (and by that time self is valid).

If you are uncomfortable with var action being settable, you can use (a common Apple pattern) of:

lazy private var _action : (String) -> () = self.method
var action { return _action }   // only the 'getter' thus `var` is actually `let`

and if you are uncomfortable with even these two, you can use private(set) to ensure that no setter is visible. And thus,

class Example {
  lazy private(set) var action: (String -()) = self.method

  func method (s:String) { println (s) }
}

Upvotes: 3

Antonio
Antonio

Reputation: 72810

You can declare the property as implicitly unwrapped optional:

let action: (String -> ())!

That's one of the few cases when implicitly unwrapped are useful and can be safely used.

Upvotes: 5

Related Questions