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

标签 ios iphone arrays swift elements

是否没有简单的方法可以从数组中删除特定元素,如果它等于给定的字符串?变通方法是找到要删除的数组元素的索引,然后 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/

相关文章:

iphone - 如何快速在相机上添加圆形 mask

iphone - 如何在终止应用程序之前保留 iPhone 应用程序状态?

iphone - 如何让 iPhone SpringBoard 显示一个应用程序包的两个或多个图标?

java - java中如何检查未初始化的数组引用?

php - 如何检查数组的某个部分是否存在于另一个数组中?

ios - 获取用户当前位置坐标 : MKMapItem vs CLLocationManager

ios - 如何在 Swift playground 中停止帧的大小变为 1024x768

ios - 在React Native中出现“未定义不是对象(评估StyleSheet.create)”错误

ios - swift : TableView

c - 如何使用指针正确地将字符串输入存储到字符数组中?