首页 > 解决方案 > Swift 创建一个函数,该函数运行另一个在调用时实现的函数。(没那么复杂)

问题描述

您好,我正在尝试创建一个 kickass 功能来显示警报并运行它的功能。Buuut 不幸的是 Xcode,我在这里感到困惑:

buttonAction:Array<(Any) -> Any)>

预期“>”完成通用参数列表

func callAlert(_ view: UIViewController, title:String, message:String, buttonName:Array<String>, buttonAction:Array<(Any) -> Any)>) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)

    for index in 0..<buttonName.count{
    alert.addAction(UIAlertAction(title: buttonName[index], style: .default, handler: { action in
    switch action.style{
    case .default:
        print("default")
        buttonAction()

    case .cancel:
        print("cancel")

    case .destructive:
            print("destructive")

        }}))}
    view.present(alert, animated: true, completion: nil)
}

我如何调用函数?请检查以下内容:

callAlert(self,
          title: "Donate type",
          message: "Thanks for your support!",
          buttonName: ["Buy me a coffee!","Something"]
    )

标签: swiftfunction

解决方案


  • 首先,我强烈建议将该方法实现UIViewController.

  • 其次,我更presentAlert()喜欢callAlert()

  • 第三,而不是两个用于按钮和动作的数组,使用一个元组数组来表示title,styleaction
    顺便说一句,未指定的类型(Any) -> Any非常非常糟糕,因为UIAlertAction处理程序显然是((UIAlertAction) -> Void)?

  • 最后添加一个可选的completion处理程序


extension UIViewController {

    func presentAlert(title: String,
                      message: String,
                      alertActions: [(title: String, style: UIAlertAction.Style, action: ((UIAlertAction) -> Void)?)],
                      completion: (() -> Void)? = nil) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        for action in alertActions {
            alert.addAction(UIAlertAction(title: action.title, style: action.style, handler: action.action))
        }
        self.present(alert, animated: true, completion: completion)
    }
}

并在里面使用它UIViewController

let buyCoffeeAction : (UIAlertAction) -> Void = { action in
    // do something
}

let somethingAction : (UIAlertAction) -> Void = { action in
    // do something
}

presentAlert(title: "Donate type",
             message: "Thanks for your support!",
             alertActions: [(title: "Buy me a coffee!", style: .default, action: buyCoffeeAction),
                            (title: "Something", style: .destructive, action: somethingAction)],
             completion: nil)

推荐阅读