Remove Specific Array Element, Equal to String - Swift

若如初见. 提交于 2019-11-28 19:30:04

问题


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 to remove, and then removeAtIndex, or to create a new array where you append all elements that are not equal to the given string. But is there no quicker way?


回答1:


You can use filter() to filter your array as follow

var strings = ["Hello","Playground","World"]

strings = strings.filter{$0 != "Hello"}

print(strings)   // "[Playground, World]"

edit/update:

Xcode 10 • Swift 4.2 or later

You can use the new RangeReplaceableCollection mutating method called removeAll(where:)

var strings = ["Hello","Playground","World"]

strings.removeAll { $0 == "Hello" }

print(strings)   // "[Playground, World]"

If you need to remove only the first occurrence of an element we ca implement a custom remove method on RangeReplaceableCollection constraining the elements to Equatable:

extension RangeReplaceableCollection where Element: Equatable {
    @discardableResult
    mutating func removeFirstElementEqual(to element: Element) -> Element? {
        guard let index = firstIndex(of: element) else { return nil }
        return remove(at: index)
    }
}

Or using a predicate for non Equatable elements:

extension RangeReplaceableCollection {
    @discardableResult
    mutating func removeFirstElement(where predicate:  @escaping ((Element) -> Bool)) -> Element? {
        guard let index = firstIndex(where: predicate) else { return nil }
        return remove(at: index)
    }
}

var strings = ["Hello","Playground","World"]
strings.removeFirstElementEqual(to: "Hello")
print(strings)   // "[Playground, World]"
strings.removeFirstElement { $0 == "Playground" }
print(strings)   // "[World]"



回答2:


It's not clear if by quicker you mean in terms of execution time or amount of code.

In the latter case you can easily create a copy using the filter method. For example, given the following array:

let array = ["1", "2", "3", "4", "5"]

you can create a copy with all elements but "2" as:

let filteredArray = array.filter { $0 != "2" }



回答3:


Using filter like suggested above is nice. But if you want to remove only one occurrence of a value or you assume there are no duplicates in the array and you want a faster algorithm, use this (in Swift3):

if let index = array.index(of: "stringToRemove") {
    array.remove(at: index)
} else {
    // not found
}



回答4:


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"
}



回答5:


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]"



回答6:


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))


来源:https://stackoverflow.com/questions/27878798/remove-specific-array-element-equal-to-string-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!