BLC BLC - 7 months ago 10
Swift Question

Cannot convert value of type '()' to expected argument type '() -> ()'

I am trying to pass a function as a parameter in Swift. In order to do that, I defined my function that takes a callback parameter as:

func foo(callback: () -> () = { _ in }) { callback() }


I then define another function that I will use:

func toBeCalled() -> () {
print("hello world")
}

foo(toBeCalled())


I get the following error:

Cannot convert value of type '()' to expected argument type '() -> ()'


Has anyone encountered this issue before? I have tried multiple things including using Void.

Thank you!

Answer

You have to pass the function not the result of that function:

foo(toBeCalled)

toBeCalled has type () -> () but when you write toBeCalled(), the function gets executed and you get the return type ().

Comments