ios 删除特定的数组元素,等于字符串 - Swift

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27878798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:17:45  来源:igfitidea点击:

Remove Specific Array Element, Equal to String - Swift

iosiphonearraysswiftelements

提问by TimWhiting

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?

如果它等于给定的字符串,是否没有简单的方法可以从数组中删除特定元素?解决方法是找到要删除的数组元素的索引,然后removeAtIndex,或者创建一个新数组,在其中附加所有不等于给定字符串的元素。但是没有更快的方法吗?

回答by Leo Dabus

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

您可以使用 filter() 过滤您的数组如下

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

strings = strings.filter { 
var strings = ["Hello","Playground","World"]

strings.removeAll { 
extension RangeReplaceableCollection where Element: Equatable {
    @discardableResult
    mutating func removeFirst(_ element: Element) -> Element? {
        guard let index = firstIndex(of: element) else { return nil }
        return remove(at: index)
    }
}
== "Hello" } print(strings) // "["Playground", "World"]\n"
!= "Hello" } print(strings) // "["Playground", "World"]\n"

edit/update:

编辑/更新:

Xcode 10 ? Swift 4.2 or later

Xcode 10?Swift 4.2 或更高版本

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

您可以使用新的RangeReplaceableCollection变异方法,称为removeAll(where:)

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

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

如果您只需要删除第一次出现的元素,我们可以实现一个自定义的删除方法来RangeReplaceableCollection将元素限制为Equatable

var strings = ["Hello","Playground","World"]
strings.removeFirst("Hello")
print(strings)   // "["Playground", "World"]\n"
strings.removeFirst { 
if let index = array.index(of: "stringToRemove") {
    array.remove(at: index)
} else {
    // not found
}
== "Playground" } print(strings) // "["World"]\n"


Or using a predicate for non Equatableelements:

或者对非Equatable元素使用谓词:

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


let filteredArray = array.filter { 
var stringsToRemove : [String] = ...
var strings : [String] = ...

strings.filter { !contains(stringsToRemove, 
 1> ["a", "b", "c", "d"].filter { !contains(["b", "c"], 
func -= (inout left: [String], right: String){
    left = left.filter{
var array = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]            
let subArrayToDelete = ["c", "d", "e", "ee"]
array = array.filter{ !subArrayToDelete.contains(
array = Array(Set(array).subtracting(subArrayToDelete))
) } print(array) // ["a", "b", "f", "g", "h", "i", "j"]
!= right} } var myArrayOfStrings:[String] = ["Hello","Playground","World"] myArrayOfStrings -= "Hello" print(myArrayOfStrings) // "[Playground, World]"
) } $R5: [String] = 2 values { [0] = "a" [1] = "d" }
) }
!= "2" }

回答by Béatrice Cassistat

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

使用上面建议的过滤器很好。但是,如果您只想删除一个值的一次出现,或者您假设数组中没有重复项并且您想要更快的算法,请使用此(在 Swift3 中):

var ra = ["a", "ab", "abc", "a", "ab"]

print(ra)                               // [["a", "ab", "abc", "a", "ab"]

ra.removeAll(where: { ##代码## == "a" })

print(ra)                               // ["ab", "abc", "ab"]

回答by Antonio

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 filtermethod. For example, given the following array:

在后一种情况下,您可以使用该filter方法轻松创建副本。例如,给定以下数组:

##代码##

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

您可以创建一个包含除“2”以外的所有元素的副本,如下所示:

##代码##

回答by GoZoner

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:

你会想要使用filter(). 如果您obj要删除单个元素(称为 say ),则filter()谓词将为{ $0 != obj }. 如果您对大型阵列重复执行此操作,则可能会出现性能问题。如果您可以推迟删除单个对象并想要删除整个子数组,请使用以下内容:

##代码##

for example:

例如:

##代码##

回答by tukbuk23

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

您可以将 filter() 与运算符重载结合使用以生成易于重复的解决方案

##代码##

回答by Tung Fam

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

如果您需要从数组中删除 subArray 那么这是使用Swift3的完美解决方案:

##代码##

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

这对你的表现更好,而不是一一删除。

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

顺便说一句,更快的解决方案是(但它会重新排列最终数组中的项目):

##代码##

回答by Roi Zakai

##代码##