我想从包含x,y和z元素的数组中删除值x的所有元素
let arr = ['a', 'b', 'c', 'b']
Run Code Online (Sandbox Code Playgroud)
如何从arr中删除值'b'的所有元素?
ilu*_*pra 113
过滤器:
let farray = arr.filter {$0 != "b"}
Run Code Online (Sandbox Code Playgroud)
Nit*_*sjp 14
var array : [String]
array = ["one","two","one"]
let itemToRemove = "one"
while array.contains(itemToRemove) {
if let itemToRemoveIndex = array.index(of: itemToRemove) {
array.remove(at: itemToRemoveIndex)
}
}
print(array)
Run Code Online (Sandbox Code Playgroud)
适用于Swift 3.0.
如果需要修改初始数组,可以使用removeAll(where:)Swift 4.2/Xcode 10 中提供的函数:
var arr = ["a", "b", "c", "b"]
arr.removeAll(where: { $0 == "b" })
print(arr) // output is ["a", "c"]
Run Code Online (Sandbox Code Playgroud)
但是,如果您使用的是 Xcode 9,则可以在Xcode9to10Preparation 中找到此函数(该库提供了 Xcode 10 中一些新函数的实现)。
根据评论编辑:
我喜欢这种方法:
var arr = ["a", "b", "c", "b"]
while let idx = arr.index(of:"b") {
arr.remove(at: idx)
}
Run Code Online (Sandbox Code Playgroud)
原始答案(编辑前):
let arr = ['a', 'b', 'c', 'b']
if let idx = arr.index(of:"b") {
arr.remove(at: idx)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34005 次 |
| 最近记录: |