Swift Array Extension
April 02, 2025 at 8:28AMNeeded a clean way to remove items from an Array. Here is what I came up with. I think it is pretty clean.
extension Array where Element: Identifiable {
// Mutating func to remove items from Array.
mutating func removeItems(withIDs idsToRemove: Set<Int>) {
self.removeAll { idsToRemove.contains($0.id) }
}
// Non-mutating func to remove items from Array and return result.
func removingItems(withIDs idsToRemove: Set<Int>) -> [Element] {
return self.filter { !idsToRemove.contains($0.id) }
}
}
Happy Coding ;-)