gpt4 book ai didi

ios - 快速传递带参数的闭包作为参数

转载 作者:行者123 更新时间:2023-11-30 11:06:11 25 4
gpt4 key购买 nike

所以我们的想法是创建一个通用警报创建器,我可以将完成处理程序传递给......

 static func makeTextFieldAlert(msg:String, title:String, onOk: @escaping (_ newText:String) -> Void ) -> UIAlertController {
let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: UIAlertController.Style.alert)

let saveAction = UIAlertAction(title: "Save", style: UIAlertAction.Style.default, handler: { alert -> Void in
let firstTextField = alertController.textFields![0] as UITextField
onOk(firstTextField.text!)
})

但是......xcode强制我把_放在那里,它强制我把@escaping放在那里......

而且......当我尝试调用这整个困惑......它甚至不会编译:

@IBAction func click(_ sender: Any) {
print("here")
let newThing:UIAlertController = Util.makeTextFieldAlert(msg: "Yes", title: "Create Thing", onOk:{_ in
ThingUtil.createThing(thing: newText)
} )

所以我尝试用 $0 代替 newText 并得到

"Anonymous closure arguments cannot be used inside a closure that has explicit arguments"

我尝试了上面的方法,得到了:

Use of unresolved identifier 'newText'

为了清楚起见,我宁愿只使用变量 newText......但此时,我只想编译它。我究竟做错了什么?谢谢!

最佳答案

这个“东西”正在我的最后编译:

class Util {
static func makeTextFieldAlert(msg:String, title:String, onOk: @escaping (_ newText:String) -> Void ) -> UIAlertController {
let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: UIAlertController.Style.alert)

let saveAction = UIAlertAction(title: "Save", style: UIAlertAction.Style.default, handler: { alert -> Void in
let firstTextField = alertController.textFields![0] as UITextField
onOk(firstTextField.text!)
})
alertController.addAction(saveAction)
return alertController
}
}


class ViewController: UIViewController {


@IBAction func click(_ sender: Any) {
print("here")
let newThing:UIAlertController = Util.makeTextFieldAlert(msg: "Yes", title: "Create Thing", onOk:{ newText in
print(newText)
} )
present(newThing, animated: true, completion: nil)
}

}

问题可能出在 ThingUtil.createThing(thing: newText) 上。您确定它需要一个字符串参数吗?

这应该是您的 ThingUtil 类 API

class ThingUtil {
static func createThing(thing:String) {

}
}

关于ios - 快速传递带参数的闭包作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52696242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com