简体   繁体   English

如何在swift中为函数类型定义一个可选变量,它可以是nil?

[英]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. 干得好。

Explaination

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.

相关问题 Swift可选类型:如何.None == nil有效 - Swift Optional type: how .None == nil works Swift:如何将函数类型值设置为可选变量? - Swift: how to set function type value to optional variable? Swift闭包“类型'Int?' 不是可选的,值永远不能为零” - Swift Closure “Type 'Int?' is not optional, value can never be nil” 如何在不将变量转换为字符串的情况下判断 Swift 中的变量是否为 Optional(nil)? - How can I tell if a variable is Optional(nil) in Swift without converting it to a String? CLLocationManager的location属性可以为nil,但这不是可选变量 - The location property of CLLocationManager can be nil, which however is not an optional variable 当 Swift 中的 Set 是可选的时,如何为 Set 定义插入 function? - How can I define insert function for Set when Set is optional in Swift? 为什么在Swift中将nil分配给可选变量是正确的? - Why assigning nil to an optional variable is true in Swift? 如何在Swift中使用函数类型参数定义函数 - How to define a function with a function type parameter in Swift 如何在 Swift 中检查一个类型是否是可选的? - How can you check if a type is Optional in Swift? 在Swift中nil文字与变量nil的可选绑定 - Optional binding of nil literal vs. variable that is nil in Swift
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM