How to remove an element of a given value from an array in Swift

前端 未结 7 1729
走了就别回头了
走了就别回头了 2020-12-28 11:34

I want to remove all elements of value x from an array that contains x, y and z elements

let arr = [\'a\', \'b\', \'c\', \'b\']

How can I r

相关标签:
7条回答
  • 2020-12-28 12:33

    A general approach is to exploit first class procedures. (However, this approach is much more powerful than what is required for your question.) To illustrate, say you want to avoid "Justin" repeatedly in many collections.

    let avoidJustin = notEqualTester ("Justin")
    
    let arrayOfUsers = // ...
    
    arrayOfUsers.filter (avoidJustin)
    
    let arrayOfFriends = // ...
    
    arrayOfFriends.filter (avoidJustin)
    

    With this, you avoid repeatedly creating a closure each time you want to avoid Justin. Here is notEqualTester which, given a that, returns a function of this that returns this != that.

    func notEqualTester<T: Equatable> (that:T) -> ((this:T) -> Bool) {
      return { (this:T) -> Bool in return this != that }
    }
    

    The returned closure for this captures the value for that - which can be useful when that is no longer available.

    0 讨论(0)
提交回复
热议问题