xcode 如何从swift数组中删除多个项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38002345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove multiple items from a swift array?
提问by Raffi
For example i have an array
例如我有一个数组
var array = [1, 2, 3, 4]
I want to remove item at index 1 then at index 3 "let it be in a for loop".
我想删除索引 1 处的项目,然后在索引 3 处“让它处于 for 循环中”。
But removing the item at index 1 will move the item at index 3 to index 2, thus messing up the second removal.
但是删除索引 1 处的项目会将索引 3 处的项目移动到索引 2,从而弄乱第二次删除。
Any suggestions ?
有什么建议 ?
回答by Luca Angeletti
Given your array
鉴于你的数组
var numbers = [1, 2, 3, 4]
and a Set
of indexes you want to remove
和Set
要删除的索引
let indexesToRemove: Set = [1, 3]
You want to remove the values "2" and "4".
您想删除值“2”和“4”。
Just write
写就好了
numbers = numbers
.enumerated()
.filter { !indexesToRemove.contains(print(numbers) // [1, 3]
.offset) }
.map { var numbers = [0, 1, 2, 3, 4, 5]
.element }
Result
结果
let indexesToBeRemoved: Set = [2, 4]
numbers = numbers
.enumerated()
.filter { !indexesToRemove.contains(var arrayString = [
[ "char" : "Z" ],
[ "char" : "Y" ],
[ "char" : "X" ],
[ "char" : "W" ],
[ "char" : "V" ],
[ "char" : "U" ],
[ "char" : "T" ],
[ "char" : "S" ]
]
let arrayIndex = [2, 3, 5]
arrayString = arrayString.enumerated()
.filter { !arrayIndex.contains(##代码##.0 + 1) }
.map { ##代码##.1 }
print(arrayString)
.offset) }
.map { ##代码##.element }
and result
回答by Seifolahi
It's simple. delete items from the end.
这很简单。从末尾删除项目。
First delete 3 and after that delete 1
先删除3,然后删除1
回答by Krunal
Swift 3:Use swift closure to perform the same operation.
Swift 3:使用 swift 闭包执行相同的操作。
If your array is like
如果你的数组就像
##代码##and indexes you want to remove
和要删除的索引
##代码##print(numbers) // [0, 1, 3, 5]
打印(数字)// [0, 1, 3, 5]
Swift 3:Here is same operation with JSON Object (dictionary)
Swift 3:这是与 JSON 对象(字典)相同的操作
##代码##[["char": "Z"], ["char": "W"], ["char": "U"], ["name": "T"], ["name": "S"]]
[["char": "Z"], ["char": "W"], ["char": "U"], ["name": "T"], ["name": "S"] ]