Home > OS >  How to intuitively check if an array property of a struct is empty?
How to intuitively check if an array property of a struct is empty?

Time:01-11

This may seem like an odd circumstance but I have structures which have arrays of structures that may sometimes be empty, but I want to check if the array itself is empty before reading it (otherwise will get an index out of range error, as the below code will result in). I'm trying to figure out the most intuitive way of doing this?

struct Item {var name: String}
struct Example {var itemArray: [Item]}

let newExample = Example(itemArray: [])

print(newExample.itemArray[0].name)

Edit: I'm just going to edit instead of deleting the question. IsEmpty is definitely an option but what if I have 2 items in the array, but I'm trying to check if the 3rd item in the array exists?

Edit2: Just going to paste in the answer code for future readers, special thanks to Lokesh SN.

struct Item {
var name: String
}
struct Example {
    var itemArray: [Item]
}
let newExample = Example(itemArray: [])
extension Collection {
subscript (safe index: Index) -> Element? {
    return indices.contains(index) ? self[index] : nil}
}

if let newItem = newExample.itemArray[safe: 0] {
    print(newItem.name)
}

CodePudding user response:

I usually introduce a 'safe' subscript within an extension that applies to all Collection types like this:

extension Collection {
    /// Returns the element at the specified index if it is within bounds, otherwise nil.
    subscript (safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

This returns an optional Element if present instead of crashing if not and is IMO a much better bargain.

Usage:

if let myUnwrappedElement = myCollection[safe: index] {
    //Do something
}
  • Related