Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drop(where: {}) remove(where: {}) function in Swift?

Is there a function in the Swift Standard library that acts on a collection, takes a predicate and returns the value removed from that collection?

Currently, I have to implement it in 2 steps:

guard let idx = allAnnotations.index(where: {$0 is MKUserLocation}) else {return}
let userLocation = allAnnotations.remove(at: idx) as! MKUserLocation

But I guess, a similar function exists.

The goal

I have the following array:

[Type1, Type1, Type1, Type1, Type1, Type1, Type2]

Type2 may or may not be present in the array. There are no other types except these two.

I need to split it onto two elements:

[Type1, Type1, Type1, Type1, Type1, Type1]

and

Type2?

That's the function I'm looking for.

like image 917
Richard Topchii Avatar asked May 04 '18 09:05

Richard Topchii


3 Answers

Swift 5 has removeAll(where)

@inlinable public mutating func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows

You can use it like this -

var array = [1,2,3]
array.removeAll(where: { $0 == 2})
print(array) // [1,3]

Apple Docs

like image 109
shannoga Avatar answered Sep 24 '22 04:09

shannoga


Here is an extension that returns an array of dropped elements:

extension Array {
    mutating func dropWhere(_ isIncluded: (Element) throws -> Bool) -> [Element] {
        do {
            let reverseArray = try filter { try isIncluded($0) }
            self = try filter { try !isIncluded($0) }

            return reverseArray
        } catch {
            return []
        }
    }
}

Just call it like you would call filter.

var array = [1, 2, 3]
let array2 = array.dropWhere { $0 > 2 }
print(array) //[1, 2]
print(array2) //[3]
like image 23
Tamás Sengel Avatar answered Sep 22 '22 04:09

Tamás Sengel


Code I've finished with:

extension Array {
  mutating func popFirstElementWith(_ predicate:(Element)->(Bool)) -> Element? {
    for (idx, element) in enumerated() {
      if predicate(element) {
        remove(at: idx)
        return element
      }
    }
    return nil
  }
}
like image 34
Richard Topchii Avatar answered Sep 25 '22 04:09

Richard Topchii