Remove Specific Array Element, Equal to String - Swift

前端 未结 8 1902
臣服心动
臣服心动 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:54

    You could use filter() in combination with operator overloading to produce an easily repeatable solution:

    func -= (inout left: [String], right: String){
        left = left.filter{$0 != right}    
    }
    
    var myArrayOfStrings:[String] = ["Hello","Playground","World"]
    
    myArrayOfStrings -= "Hello"
    
    print(myArrayOfStrings)   // "[Playground, World]"
    
    0 讨论(0)
  • 2020-12-23 16:57

    if you need to delete subArray from array then this is a perfect solution using Swift3:

    var array = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]            
    let subArrayToDelete = ["c", "d", "e", "ee"]
    array = array.filter{ !subArrayToDelete.contains($0) }
    print(array) // ["a", "b", "f", "g", "h", "i", "j"]
    

    this is better for your performance rather than deleting one by one.

    btw even faster solution is (but it will rearrange items in the final array):

    array = Array(Set(array).subtracting(subArrayToDelete))
    
    0 讨论(0)
提交回复
热议问题