我有一个具有多个属性的数据模型对象。我有一个动态数组,它有时会在其中包含一些但不是全部的对象属性。
如何安全地检查数组是否在其索引处
数据模型
class Order{
var item0:String?
var item1:String?
var item2:String?
}
大批:
var myArray = [String]()
保护语句是我在检查数组内是否有不同索引处的元素时遇到问题的地方。
顺便说一句,数组里面永远不会有超过 3 个元素。
let order = Order()
order.item0 = "hat"
order.item1 = "sneakers"
myArray.append(order.item0)
myArray.append(order.item1)
//sometimes there may or may not be item2
let placedOrder = Order
//These guard statements aren't working
guard case let placedOrder.item0 = myArray[0] else {return}
guard case let placedOrder.item1 = myArray[1] else {return}
//There isn't anything at myArray[2] but I need to safely check anyway
guard case let placedOrder.item2 = myArray[2] else {return}