我有一个包含多个属性的数据模型对象。我有一个动态数组,有时会有一些但不是所有的对象属性。
如何安全地检查数组是否为索引
的DataModel
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}
答案 0 :(得分:0)
1st数组应保存数据模型类型,而不是它的属性:
var orders = [Order]()
//changed the array's name from myArray to orders instead
2nd将数据模型对象添加到数组中:
let orderOne = Order()
orders.append(orderOne)
遍历数组的第3个循环,检查元素的属性是否为nil:
for order in orders{
if order.item0 != nil{
//do something with order.item0
}
if order.item1 != nil{
//do something with order.item1
}
if order.item2 != nil{
//do something with order.item2
}
}