Home > OS >  Swift - use a function like .first on an array, but to get the second element
Swift - use a function like .first on an array, but to get the second element

Time:05-05

I use .first to receive elements from an array. When the array is empty, it returns a standard value:

plant.waterEventArrayDetailed.first?.plantRating ?? 0

I would like to acces the second value. But, sometimes the array is empty, so using a simple [1] would crash. How can I get the function to return the second value?

CodePudding user response:

Now there is :)

extension Collection {
    var second: Element? { dropFirst().first }
}

print(["a", "b", "c"].second) // => Optional("b")

CodePudding user response:

Should've thought some more. You can drop the first element and then access the new first element:

plant.waterEventArrayDetailed.dropFirst().first?.plantRating ?? 0
  • Related