Search code examples
arraysswiftswift2datamodeloptional-values

Swift: array check for object at index


I have an data model object with several properties. I have a dynamic array that will sometimes have some but not all of the object properties inside of it.

How do I safely check if the array as anything at it's index

DataModel

class Order{
     var item0:String?
     var item1:String?
     var item2:String?
}

Array:

var myArray = [String]()

The guard statements are where I'm having issues checking to see if there are elements inside the array at different indexes.

Btw the array will never have more then 3 elements inside of it.

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}

Solution

  • 1st The array should hold the data model type and not it's properties:

    var orders = [Order]() 
    //changed the array's name from myArray to orders instead
    

    2nd Add the data model object to the array:

    let orderOne = Order()
    
    orders.append(orderOne)
    

    3rd loop through the array, check that the element's properties aren't 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
        }
    }