【问题标题】:Check if optional array is empty in Swift检查 Swift 中的可选数组是否为空
【发布时间】:2020-06-16 18:57:47
【问题描述】:

我意识到有很多关于 SO 的问题都有关于此的答案,但由于某种原因,我无法工作。我想做的就是测试一个数组是否至少有一个成员。出于某种原因,Apple 在 Swift 中使这变得复杂,不像在 Objective-C 中你刚刚测试了 count>=1。数组为空时代码崩溃。

这是我的代码:

let quotearray = myquotations?.quotations

if (quotearray?.isEmpty == false) {

let item = quotearray[ Int(arc4random_uniform( UInt32(quotearray.count))) ] //ERROR HERE

}

但是,我收到一个错误:

Value of optional type '[myChatVC.Quotation]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[myChatVC.Quotation]'.

链接或强制展开的修复选项都不能解决错误。我也试过:

if array != nil && array!. count > 0  and if let thearray = quotearray 

但这些都不起作用

感谢您的任何建议。

【问题讨论】:

    标签: arrays swift optional is-empty


    【解决方案1】:

    randomElement 已经存在,所以不要重新发明轮子:

    var pepBoys: [String]? = ["manny", "moe", "jack"]
    // ... imagine pepBoys might get set to nil or an empty array here ...
    if let randomPepBoy = pepBoys?.randomElement() {
        print(randomPepBoy)
    }
    

    如果pepBoysnil 或为空,if let 将安全失败。

    【讨论】:

    • 这段代码也能正常工作。将其标记为正确,因为此版本比 @Frankenstein 的版本略短,后者也有效。
    【解决方案2】:

    您可以解开可选数组并像这样使用它,也可以使用新的Int.random(in:) 语法来生成随机Ints:

    if let unwrappedArray = quotearray,
        !unwrappedArray.isEmpty {
        let item = unwrappedArray[Int.random(in: 0..<unwrappedArray.count)]
    }
    

    【讨论】:

    • 同时使用 if let 和 isEmpty 看起来是测试具有元素的可选数组的好方法
    • 总有改进的余地。就像我刚刚使用 unwrappedArray.isEmpty == false 语句或直接在数组上调用 randomElement 一样使 bool 检查更短。
    【解决方案3】:

    检查第一个元素是否存在

    var arr: [Int]? = [1, 2, 3, 4]
    if let el = arr?.first{
      print(el)
    }
    

    【讨论】:

      【解决方案4】:

      我建议使用保护语句

      guard let array = optionalArray, !array.isEmpty else { return }
      

      【讨论】:

        猜你喜欢
        • 2015-02-19
        • 2017-09-13
        • 2011-11-04
        • 2016-04-19
        • 1970-01-01
        • 1970-01-01
        • 2012-05-17
        • 2022-01-25
        • 2011-07-31
        相关资源
        最近更新 更多