Swift创建一个函数,该函数运行调用时实现的另一个函数。(没有那么复杂)

Swift创建一个函数,该函数运行调用时实现的另一个函数。(没有那么复杂),swift,function,Swift,Function,你好,我正在尝试创建一个kickass函数来显示警报并运行它的函数。不幸的是,Buuut Xcode和我在这里感到困惑: buttonAction:Array<(Any) -> Any)> 首先,我强烈建议将该方法实现为UIViewController的扩展 其次,我更喜欢presentAlert()而不是callAlert() 第三,按钮和动作的数组不是两个,而是一个元组数组,用于标题,样式和动作 顺便说一下,未指定类型(Any)->Any非常糟糕,因为UIAlertAc

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

buttonAction:Array<(Any) -> Any)>
  • 首先,我强烈建议将该方法实现为
    UIViewController
    扩展

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

  • 第三,按钮和动作的数组不是两个,而是一个元组数组,用于
    标题
    样式
    动作

    顺便说一下,未指定类型
    (Any)->Any
    非常糟糕,因为
    UIAlertAction
    处理程序显然是
    ((UIAlertAction)->Void)

  • 最后添加一个可选的
    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)

如果多余的
被删除,那么你就可以继续下一个错误了。有没有办法把funcA()和funcB()放在一个数组中?@KaanKaray所以你认为写闭包和function之间的区别是有意义的,如果是,怎么做?@shu Khan我不想用额外的功能来确定可以添加多少警报按钮,我想他显示的方式更有意义,因为某种原因。我没有使用他制作的东西,实际上让我自己更容易,
alertActions:[(标题:“给我买杯咖啡!”,风格:。默认,动作:{action in self.loadProducts(donateCoffee)}),
谢谢你的输入,顺便说一句!:)顺便说一句,我仍然不相信,但没问题
callAlert(self,
          title: "Donate type",
          message: "Thanks for your support!",
          buttonName: ["Buy me a coffee!","Something"]
    )
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)
    }
}
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)