gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:59:13 28 4
gpt4 key购买 nike

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

最佳答案

您可以使用 filter() 来过滤您的数组,如下所示

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

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

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

编辑/更新:

Xcode 10 • Swift 4.2 或更高版本

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

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

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

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

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

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

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

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

var strings = ["Hello","Playground","World"]
strings.removeFirst("Hello")
print(strings) // "["Playground", "World"]\n"
strings.removeFirst { $0 == "Playground" }
print(strings) // "["World"]\n"

关于ios - 删除特定数组元素,等于字符串 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27878798/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com