[英]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. 我想有一个变量来保存一个函数,但是它被初始化为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. 如果我删除?,我也会得到同样的错误。
你只需将它包装在括号中:
var OnClick: ((UIButton!) -> ())? = nil
Adding to Cezary's correct answer here. 在这里添加到Cezary的正确答案。 If someone need in detail explanation.
如果有人需要详细说明。 Here you go.
干得好。
var OnClick: (UIButton!) -> ()?
defines a variable named OnClick which stores a function type. 定义一个名为OnClick的变量,它存储一个函数类型。 The function accepts a
Implicitly Unwrapped Optional
and return optional Void
. 该函数接受
Implicitly Unwrapped Optional
并返回可选的Void
。 Note that optional is not the function itself but return type of the function. 请注意,optional不是函数本身,而是函数的返回类型。 So you can't assign nil.
所以你不能分配nil。
var OnClick: ((UIButton!) -> ())?
defines a variable named OnClick which stores a optional function
. 定义一个名为OnClick的变量,它存储一个
optional function
。 The function is such that accepts Implicitly Unwrapped Optional
and return Void
. 该函数接受
Implicitly Unwrapped Optional
并返回Void
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.