[英]Swift passing closure with arguments AS an argument
So the idea is to make a general purpose alert creator that I can pass a completion handler to.... 因此,该想法是使通用警报创建者可以将完成处理程序传递给...。
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!)
})
However.....xcode forces me to put the _ there and it forces me to put @escaping there.... 但是..... xcode迫使我将_放在这里,并且迫使我将@转义到那里....
And....when I try to call this whole mess....It won't even compile: 还有.....当我尝试称其为一团糟....它甚至不会编译:
@IBAction func click(_ sender: Any) {
print("here")
let newThing:UIAlertController = Util.makeTextFieldAlert(msg: "Yes", title: "Create Thing", onOk:{_ in
ThingUtil.createThing(thing: newText)
} )
So I try $0 in place of newText
and I get 所以我尝试$ 0代替
newText
我得到
"Anonymous closure arguments cannot be used inside a closure that has explicit arguments"
“匿名闭包参数不能在具有显式参数的闭包内使用”
And I try what I have above and I get: 我尝试上面的东西,然后得到:
Use of unresolved identifier 'newText'
使用未解决的标识符“ newText”
I would prefer to just use the variable newText for the sake of clarity....but at this point, I just want it to compile. 为了清楚起见,我宁愿只使用变量newText。...但是在这一点上,我只希望它可以编译。 What am I doing wrong?
我究竟做错了什么? Thank you!
谢谢!
This "thing" is compiling at my end: 这个“东西”在我的最后编译:
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)
}
}
May be the problem is this ThingUtil.createThing(thing: newText)
. 可能是这个问题
ThingUtil.createThing(thing: newText)
。 Are you sure it takes a string argument? 您确定需要一个字符串参数吗?
This should be your ThingUtil class API 这应该是您的ThingUtil类API
class ThingUtil {
static func createThing(thing:String) {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.