【问题标题】:How to define in swift an optional variable for a function type, which can be nil?如何在swift中为函数类型定义一个可选变量,它可以是nil?
【发布时间】:2014-06-04 14:31:31
【问题描述】:

我想要一个变量来保存一个函数,但它被初始化为 nil。我正在尝试将其设为可选,但出现错误。

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

我收到此错误

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

如果我删除 ?,我也会得到同样的错误。

【问题讨论】:

    标签: swift


    【解决方案1】:

    你只需要把它用括号括起来:

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

    【讨论】:

      【解决方案2】:

      在此处添加 Cezary 的正确答案。如果有人需要详细解释。给你。

      说明

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

      定义了一个名为 OnClick 的变量,它存储了一个函数类型。该函数接受Implicitly Unwrapped Optional 并返回可选的Void。请注意, optional 不是函数本身,而是函数的返回类型。所以你不能分配 nil。

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

      定义了一个名为 OnClick 的变量,它存储了一个optional function。该函数接受Implicitly Unwrapped Optional 并返回Void

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-13
        相关资源
        最近更新 更多