【问题标题】:Unwrap multiple optionals in swift快速解开多个选项
【发布时间】:2021-10-02 02:21:05
【问题描述】:

我现在正在开发一个 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)

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

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

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

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

我只能处理title为String,message为String的情况。 我也想关心标题为 nil 但消息为字符串,或标题为字符串而消息为 nil 的情况。

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

【问题讨论】:

  • 刚刚发现 UI 警报控制器对标题和消息都采用可选值,所以可能我不需要解开这个... UIAlertController(title: String?, message: String?,首选样式:UIAlertController.Style)

标签: ios swift alert optional optional-parameters


【解决方案1】:

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

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

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

func showAlert(title: String?, message: 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)
}

【讨论】:

  • 非常感谢!是的,我刚刚看到自动完成告诉我它需要可选值...但是感谢您的帮助和清晰的解释!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-10
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 2015-01-28
  • 1970-01-01
  • 2023-03-19
相关资源
最近更新 更多