qadram
qadram

Reputation: 163

How to define in swift an optional variable for a function type, which can be nil?

I would like to have a variable to hold a function, but which is initialized to nil. I'm trying to make it an optional, but I get an error.

var OnClick: (UIButton!) -> ()? = nil

I get this error

Could not find an overload for '__conversion' that accepts the supplied arguments

If I remove the ?, I also get the same error.

Upvotes: 12

Views: 4748

Answers (2)

MadNik
MadNik

Reputation: 7793

Adding to Cezary's correct answer here. If someone need in detail explanation. Here you go.

Explaination

var OnClick: (UIButton!) -> ()?

defines a variable named OnClick which stores a function type. The function accepts a Implicitly Unwrapped Optional and return optional Void. Note that optional is not the function itself but return type of the function. So you can't assign nil.

var OnClick: ((UIButton!) -> ())?

defines a variable named OnClick which stores a optional function. The function is such that accepts Implicitly Unwrapped Optional and return Void.

Upvotes: 2

Cezary Wojcik
Cezary Wojcik

Reputation: 21845

You just have to wrap it in parentheses:

var OnClick: ((UIButton!) -> ())? = nil

Upvotes: 23

Related Questions