OGeek|极客世界-中国程序员成长平台

标题: ios - 使用闭包作为参数而不使用尾随闭包 Swift [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 22:15
标题: ios - 使用闭包作为参数而不使用尾随闭包 Swift

使用尾随闭包语法时,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)")
}

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

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



Best Answer-推荐答案


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

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)

关于ios - 使用闭包作为参数而不使用尾随闭包 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54740478/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4