Manuel Manuel - 4 months ago 21
Swift Question

How to pass closure with argument as argument and execute it?

Initializer of class

A
takes an optional closure as argument:

class A {
var closure: ()?

init(closure: closure()?) {
self.closure = closure
self.closure
}
}


I want to pass a function with an argument as the closure:

class B {
let a = A(closure: action(1)) // This throws the error: Cannot convert value of type '()' to expected argument type '(() -> Void)?'

func action(i: Int) {
//...
}
}


Class
A
should execute the closure
action
with argument
i
.

I am not sure about how to write this correctly, see error in code comment above. What has to be changed?

Answer

The problem is that closure()? is not a type. And ()? is a type, but it is probably not the type you want.

If you want var closure to have as its value a certain kind of function, you need to use the type of that function in the declaration, e.g.

var closure: (Int) -> Void

Similarly, if you want init(closure:) to take as its parameter a certain kind of function, you need to use the type of that function in the declaration, e.g.

init(closure: (Int) -> Void) {