Swift:数组检查索引处的对象
Swift: array check for object at index
我有一个具有多个属性的数据模型对象。我有一个动态数组,它有时会包含一些但不是全部的对象属性。
我如何安全地检查数组是否在它的索引处
数据模型
class Order{
var item0:String?
var item1:String?
var item2:String?
}
数组:
var myArray = [String]()
guard 语句是我在检查数组中是否有不同索引处的元素时遇到问题的地方。
顺便说一句,数组中的元素永远不会超过 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}
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
}
}
我有一个具有多个属性的数据模型对象。我有一个动态数组,它有时会包含一些但不是全部的对象属性。
我如何安全地检查数组是否在它的索引处
数据模型
class Order{
var item0:String?
var item1:String?
var item2:String?
}
数组:
var myArray = [String]()
guard 语句是我在检查数组中是否有不同索引处的元素时遇到问题的地方。
顺便说一句,数组中的元素永远不会超过 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}
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
}
}