【发布时间】: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