【问题标题】:Use function in closure在闭包中使用函数
【发布时间】:2016-08-09 23:43:39
【问题描述】:

我正在尝试在闭包中使用函数,但收到错误消息“无法将 () 类型的值转换为闭包结果类型 Bool”。以下代码演示了该错误。我怎样才能做到这一点?

func test1(){
    test2(){ success in
        self.test1()
    }
}

func test2(completionHandler: (Bool) -> Bool){
    completionHandler(true)
}

【问题讨论】:

    标签: swift


    【解决方案1】:

    您指定test2 闭包返回Bool,因此返回一个:

    func test1(){
        test2 { (success) -> Bool in
            test1()
            return success
        }
    }
    

    如果您不想从中返回值,请让 test2 的闭包返回 void:

    func test1(){
        test2 { (success) in
            test1()
        }
    }
    
    func test2(completionHandler: (Bool) -> Void){
        completionHandler(true)
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 2018-03-24
      相关资源
      最近更新 更多