检查Swift中的可选数组是否为空

问题描述 投票:0回答:1

我知道在SO上有很多关于这个问题的答案,但是不知道为什么,我不能让任何一个问题发挥作用。我想做的就是测试一个数组是否至少有一个成员。由于某些原因,苹果公司在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个回答
2
投票

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)
}

这个... ... if let 会安全失败,如果 pepBoysnil 或空。


0
投票

我建议使用保护语句

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


0
投票

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

if let unwrappedArray = quotearray,
    !unwrappedArray.isEmpty {
    let item = unwrappedArray[Int.random(in: 0..<unwrappedArray.count)]
}
© www.soinside.com 2019 - 2024. All rights reserved.