Swift 中的回调函数语法 [英] Callback function syntax in Swift
本文介绍了Swift 中的回调函数语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将一个函数传递给另一个函数,然后执行传递给它的函数并将一个变量传递给它.
I am attempting pass a function to another function and then have the passed function executed passing to it a variable.
这是我的代码:
func showStandardPrompt(prompt:String,view: UIViewController,numberInput: Bool, callback: (()->(String))?) {
let alert = UIAlertController(title: "Input Data", message: prompt, preferredStyle: .Alert)
alert.addTextFieldWithConfigurationHandler { (textField) in
if numberInput {
textField.keyboardType = .NumberPad
}
}
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
let field = alert.textFields![0] as UITextField
callback?(field.text!)
}
alert.addAction(OKAction)
let CancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
alert.addAction(CancelAction)
view.presentViewController(alert,animated: true, completion: nil)
}
我得到的错误是
callback?(field.text!)
错误是无法将 'String' 的值类型转换为预期的参数类型 '()'.我知道这是一个语法问题 - 只是不知道它应该是什么.
The error is "Cannot convert value type of 'String' to expected argument type '()'. I know it's a matter of syntax - just don't know what it should be.
推荐答案
Rob 的回答是正确的,虽然我想分享一个简单的工作回调/完成处理程序的示例,您可以下载下面的示例项目并进行实验getBoolValue
的输入.
Rob's answer is correct, though I'd like to share an example of a simple working callback / completion handler, you can download an example project below and experiment with the getBoolValue
's input.
func getBoolValue(number : Int, completion: (Bool)->()) {
if number > 5 {
completion(true)
} else {
completion(false)
}
}
getBoolValue(number: 2) { (result) -> () in
// do stuff with the result
print(result)
}
重要的理解:
(String)->() // takes a String returns void
()->(String) // takes void returns a String
这篇关于Swift 中的回调函数语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文