Remove Specific Array Element, Equal to String - Swift

前端 未结 8 1953
臣服心动
臣服心动 2020-12-23 16:07

Is there no easy way to remove a specific element from an array, if it is equal to a given string? The workarounds are to find the index of the element of the array you wish

8条回答
  •  孤城傲影
    2020-12-23 16:38

    You'll want to use filter(). If you have a single element (called say obj) to remove, then the filter() predicate will be { $0 != obj }. If you do this repeatedly for a large array this might be a performance issue. If you can defer removing individual objects and want to remove an entire sub-array then use something like:

    var stringsToRemove : [String] = ...
    var strings : [String] = ...
    
    strings.filter { !contains(stringsToRemove, $0) }
    

    for example:

     1> ["a", "b", "c", "d"].filter { !contains(["b", "c"], $0) }
    $R5: [String] = 2 values {
      [0] = "a"
      [1] = "d"
    }
    

提交回复
热议问题