swift - 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"]
)
解决方案
首先,我强烈建议将该方法实现为
UIViewController
.其次,我更
presentAlert()
喜欢callAlert()
第三,而不是两个用于按钮和动作的数组,使用一个元组数组来表示
title
,style
和action
。
顺便说一句,未指定的类型(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)
推荐阅读
- r - (R) Markdown:如何在不插入空行的情况下定义新段落?
- php - 从 SHOUTcast 脚本 print_r ($vc_shoutcast->LISTENERS) 中删除重复项;
- python - 使用 Notebook 中的名称酸洗列表并在 Notebook2 中取消酸洗它们
- python - ModuleNotFoundError:即使安装后也没有名为“selenium”的模块
- java - Java 服务器的语言支持在过去 3 分钟内崩溃了 5 次。服务器不会重启
- xcode - 我在哪里可以删除我在 macOS Big Sur 中使用 Xcode 安装的 App 小部件?
- typescript - 为什么依赖于推断的通用参数的接口成员解析为“未知”?
- r - 在 case_when 中使用列名作为失败输出
- ios - 一个视图控制器中的 2 个表视图在 tableview.reloadData() 上出现错误
- ruby-on-rails - Rails 6 Capistrano 部署到生产不提供 css 和 js 文件