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

时间:2018-10-08 06:03:18

标签: ios swift closures

所以这个想法是让通用警报创建者可以将完成处理程序传递给...。

 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迫使我将_放到那里,并且迫使我将@转义到那里。

还有...。当我尝试称这整个烂摊子时。...甚至无法编译:

@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,我得到

  

“匿名闭包参数不能在具有   显式参数”

然后尝试上面的操作,我会得到:

  

使用未解决的标识符“ newText”

为了清楚起见,我宁愿只使用变量newText。...但是在这一点上,我只希望它可以编译。我究竟做错了什么?谢谢!

1 个答案:

答案 0 :(得分:0)

这个“东西”正在我的末端编译:

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) {

    }
}
相关问题