Computed property of closures

I would like to use a closure as a computed property. I mean something like the code below.

class MyClass {
    typealias myFuncType = () -> (Void)
    private var _myAction:myFuncType
    var myAction:myFuncType = {
    set(newAction){
        self._myAction = newAction
       }
    }
}

Is it possible or will the compiler think that as I opened a bracked it must be the closure definition?

Upvotes: 0

Views: 752

Answers (1)

Antonio
Antonio

Reputation: 72810

Closures (and functions) are advertised as first class citizens in swift, so you can store them in variables and properties like any other data type.

That said, your code is almost good, you just have to remove the '=' because otherwise it's considered as a stored property with inline initialization. The correct code is:

var myAction:myFuncType {
    set(newAction) {
        self._myAction = newAction
    }
    get { // see notes below
        return _myAction
    }
}

Some notes:

  • there's no need to use a computed property backed by a stored property - your code is equivalent to:

    class MyClass {
        typealias myFuncType = () -> (Void)
    
        var myAction: myFuncType
    }
    
  • if you need to make additional processing when setting the property, make use of Property Observers: willSet and didSet

  • in a computed property, if you implement a setter, you must also provide a getter

Upvotes: 1

Related Questions