Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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.

like image 976
qadram Avatar asked Jun 04 '14 14:06

qadram


People also ask

How do you declare an optional variable in Swift?

How to declare an Optional? You can simply represent a Data type as Optional by appending ! or ? to the Type . If an optional contains a value in it, it returns value as Optional<Value> , if not it returns nil .

How can we unwrap an optional variable A?

A common way of unwrapping optionals is with if let syntax, which unwraps with a condition. If there was a value inside the optional then you can use it, but if there wasn't the condition fails. For example: if let unwrapped = name { print("\(unwrapped.


2 Answers

You just have to wrap it in parentheses:

var OnClick: ((UIButton!) -> ())? = nil
like image 136
Cezary Wojcik Avatar answered Oct 14 '22 10:10

Cezary Wojcik


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.

like image 44
MadNik Avatar answered Oct 14 '22 11:10

MadNik