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

前端 未结 7 1728
走了就别回头了
走了就别回头了 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:09

    EDITED according to comments:

    I like this approach:

    var arr = ["a", "b", "c", "b"]
    
    while let idx = arr.index(of:"b") {
        arr.remove(at: idx)
    }
    

    Original answer (before editing):

    let arr = ['a', 'b', 'c', 'b']
    
    if let idx = arr.index(of:"b") {
        arr.remove(at: idx)
    }
    
    0 讨论(0)
  • 2020-12-28 12:10

    In Swift 3 I simply do:

    arr = arr.filter { $0 != "a" } 
    

    .filter, .sort and .map are great for saving time and solve lots of problems with little code.

    This article has good examples and explain the differences and how they work: https://useyourloaf.com/blog/swift-guide-to-map-filter-reduce/

    0 讨论(0)
  • 2020-12-28 12:17

    If you need to modify initial array, you can use the function removeAll(where:) that is available in Swift 4.2/Xcode 10:

    var arr = ["a", "b", "c", "b"]
    arr.removeAll(where: { $0 == "b" })
    print(arr) // output is ["a", "c"]
    

    However, if you are using Xcode 9 you can find this function in Xcode9to10Preparation (this library provides implementations of some new functions from Xcode 10).

    0 讨论(0)
  • 2020-12-28 12:17

    If you have more than one element to remove, thanks to first answer.

     var mainArray = ["a", "b", "qw", "qe"]
     let thingsToRemoveArray = ["qw", "b"] 
    
    
            for k in thingsToRemoveArray {
                mainArray =  mainArray.filter {$0 != k}
              }
    
    0 讨论(0)
  • 2020-12-28 12:29
    var array : [String]
    array = ["one","two","one"]
    
    let itemToRemove = "one"
    
    while array.contains(itemToRemove) {
        if let itemToRemoveIndex = array.index(of: itemToRemove) {
            array.remove(at: itemToRemoveIndex)
        }
    }
    
    print(array)
    

    Works on Swift 3.0.

    0 讨论(0)
  • 2020-12-28 12:32

    A filter:

     let farray = arr.filter {$0 != "b"} 
    
    0 讨论(0)
提交回复
热议问题