微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

快速解开多个选项

如何解决快速解开多个选项

我现在正在从事一个 Swift 项目,并且正在开发应用程序的同时学习这门语言。我正在尝试创建一个函数调用“警报弹出窗口”,并有一个关于可选解包的问题。

func showAlert(title: String?,message: String?,actions: [UIAlertAction],style: UIAlertController.Style) {
    let title = title ?? nil
    let message = message ?? nil

    print("alert \(title),\(message),") // get optional value or nil,not String and nil...
        
    let alert = UIAlertController(title: title,message: message,preferredStyle: style)
    actions.forEach { alert.addAction($0)}
    present(alert,animated: true)
}

由于我需要在应用程序中显示多个警报弹出窗口,因此我创建了一个自定义函数“showAlert”,并且我想像下面的代码一样调用这个函数

showAlert(title: "delete",message: nil,actions: [deleteAction],style: .alert)

问题是标题和消息值可以是字符串或零(例如...警报控制器只显示标题但消息),所以我需要澄清标题和消息是否包含值。>

在这里要做的是,检查标题和消息值,并将 String 或 nil 应用到这部分,let alert = UIAlertController(title: title,preferredStyle: style)。 我阅读了一些关于可选绑定的文章,但是如果我使用它编写这段代码

func showAlert(title: String?,style: UIAlertController.Style) {

    if let title = title,let message = message {
        print("alert \(title),") // get optional value
        
        let alert = UIAlertController(title: title,preferredStyle: style)
        actions.forEach { alert.addAction($0)}
        present(alert,animated: true)
    }
}

我只能处理title为String,message为String的情况。 我也想关心 title 为 nil 但 message 为 String 的情况,或者 title 为 String 且 message 为 nil 的情况。

那么我如何编写在 showAlert 的标题和消息中采用 String 或 nil 的代码,并在这部分 UIAlertController(title: title,preferredStyle: style) 中应用 String 或 nil?

解决方法

你不需要做任何事情。 UIAlertController.init(title:message:preferredStyle:) 具有以下签名。

convenience init(title: String?,message: String?,preferredStyle: UIAlertController.Style)

titlemessage 都已经是 String? 类型,因此您可以传递函数参数中收到的任何内容,而无需像在第一个版本中所做的那样检查任何选项。

func showAlert(title: String?,actions: [UIAlertAction],style: UIAlertController.Style) {
    // Notice how the redundant declarations in your version have been removed
    print("alert \(title),\(message),") // get optional value or nil,not String and nil...
        
    let alert = UIAlertController(title: title,message: message,preferredStyle: style)
    actions.forEach { alert.addAction($0)}
    present(alert,animated: true)
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?