Home > Net >  Find multiple elements that are equal to a condition in array?
Find multiple elements that are equal to a condition in array?

Time:07-08

I am a new to SwiftUI, so I apologise if this a dumb question but I came upon a problem that I cant find a solution to.

I am searching something similar to this code below, but instead of finding the first element I would like to retrieve all elements that have the status == 0.

if let new = array.first(where: {$0.status == 0}) {
   // do something with foo
} else {
   // item could not be found
}

CodePudding user response:

Swift collections have a filter method which allows you to select all elements that match a given condition. You already have a matching condition, so to adapt your example text you'd write:

let newItems = array.filter { $0.status == 0 }
  • Related