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

Tim*_*ing 52 arrays iphone elements ios swift

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

Leo*_*bus 127

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

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

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

print(strings)   // "[Playground, World]"
Run Code Online (Sandbox Code Playgroud)

编辑/更新:

Xcode 10•Swift 4.2

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

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

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

print(strings)   // "[Playground, World]"
Run Code Online (Sandbox Code Playgroud)


Ant*_*nio 9

目前尚不清楚你的执行时间或代码数量是否更快.

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

let array = ["1", "2", "3", "4", "5"]
Run Code Online (Sandbox Code Playgroud)

您可以创建一个包含所有元素的副本,但"2"为:

let filteredArray = array.filter { $0 != "2" }
Run Code Online (Sandbox Code Playgroud)

  • @LeonardoSavioDabus:哈哈,是的,但我的妻子在写答案的时候问我一个问题我打断了......所以我赢了;-) (7认同)
  • 哈哈哈,我们完美同步,但我快了7秒.:) (2认同)

Béa*_*tat 9

使用上面建议的过滤器很不错.但是,如果您只想删除一个值的某个值,或者您认为数组中没有重复项并且您想要更快的算法,请使用此(在Swift3中):

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


GoZ*_*ner 7

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

var stringsToRemove : [String] = ...
var strings : [String] = ...

strings.filter { !contains(stringsToRemove, $0) }
Run Code Online (Sandbox Code Playgroud)

例如:

 1> ["a", "b", "c", "d"].filter { !contains(["b", "c"], $0) }
$R5: [String] = 2 values {
  [0] = "a"
  [1] = "d"
}
Run Code Online (Sandbox Code Playgroud)