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)
目前尚不清楚你的执行时间或代码数量是否更快.
在后一种情况下,您可以使用该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)
使用上面建议的过滤器很不错.但是,如果您只想删除一个值的某个值,或者您认为数组中没有重复项并且您想要更快的算法,请使用此(在Swift3中):
if let index = array.index(of: "stringToRemove") {
array.remove(at: index)
} else {
// not found
}
Run Code Online (Sandbox Code Playgroud)
你会想要使用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)