【问题标题】:Using closures as parameters without trailing closures Swift使用闭包作为参数而不使用尾随闭包 Swift
【发布时间】:2019-07-11 10:27:26
【问题描述】:

使用尾随闭包语法时,pass a function as a parameter of another function 似乎很容易。

但是我想在不使用尾随闭包语法的情况下这样做

func doSomethingTwo(closure: (String) -> Void) {
    closure("AAA")
}

doSomethingTwo(closure: print("TEST") )

给予 无法将类型 '()' 的值转换为预期的参数类型 '(String) -> Void'

我知道

doSomethingTwo{ (test: String) in
    print ("\(test)")
}

有效,但希望没有尾随闭包语法。

这不是家庭作业问题,我正在查看教程并进行了研究,但没有给我这个问题的答案。

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    如果您收到此错误,您可能缺少= 符号

    例如

    yourClosure = { variable: VariableType in 
        print(variable)
    }
    

    【讨论】:

      【解决方案2】:

      你需要定义自己的打印方法作为参数传递:

      func doSomethingTwo(closure: (String) -> ()) {
          // when you call the closure you need to pass the string to be printed
          closure("TEST")
      }
      

      定义打印将传递给闭包的字符串的方法:

      let closure: (String) -> () = { print($0) }
      

      那么你可以随意调用它:

      doSomethingTwo(closure: closure)
      

      【讨论】:

        【解决方案3】:

        这就是你调用函数的方式

        doSomethingTwo()
        

        如果我们按照模式,把()放在前面,然后附带它的参数,你会得到这样的东西。

        doSomethingTwo(closure: { (str) in
             print(str)
        })
        

        顺便说一句,Xcode 会帮你完成。但是如果你不想要它的帮助,当你有这个的时候,不要tap,你自己输入其余的。

        【讨论】:

          【解决方案4】:

          您没有正确调用该函数。你应该这样称呼它:

          doSomethingTwo(closure: { (text) in
          print(text)
          })
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2016-04-14
            • 2020-10-09
            • 2021-01-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-03-27
            相关资源
            最近更新 更多