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.
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 .
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.
You just have to wrap it in parentheses:
var OnClick: ((UIButton!) -> ())? = nil
Adding to Cezary's correct answer here. If someone need in detail explanation. Here you go.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With