我在从数组中删除项目时遇到问题,我尝试解决很长时间,但我无法解决
我的问题是:我有字典[Int:String]包含项目,用户从表视图单元格中选择这些项目以删除它,此字典具有来自字符串类型的项目,并且键键是 indexPath.row以下是我的字典代码:
var dictionaryOfItems = [Int:String]()
dictionaryOfItems.updateValue("Banana", forKey: 0)
dictionaryOfItems.updateValue("Cucumber", forKey: 3)
我有一个包含项目类型字符串数组的数组以下代码是我的数组:
var array :[String] = ["Banana","Apple","Orange","Cucumber","lettuce","Milk","Tea"]
我需要从字典包含它的数组中删除项目
当我尝试从数组中删除项目时,我得到错误消息索引超出范围,请问我该如何修复它
以下是我的完整代码:
var array :[String] = ["Banana","Apple","Orange","Cucumber","lettuce","Milk","Tea"]
var dictionaryOfItems = [Int:String]()
dictionaryOfItems.updateValue("Banana", forKey: 0)
dictionaryOfItems.updateValue("Cucumber", forKey: 3)
for (index,_) in dictionaryOfItems {
if array[index] == dictionaryOfItems[index] {
array.remove(at: index)
}
}
无需从数组中显式删除项目,只需使用谓词filter
:
- 过滤我们的元素,其关联的数组索引(例如
idx
)对应于字典中的键dictionaryOfItems
其值等于数组元素的值。
例如:
array = array.enumerated()
.filter { (idx, _) in dictionaryOfItems[idx] != array[idx] }
.map { $0.1 }
print(array) // ["Apple", "Orange", "lettuce", "Milk", "Tea"]
然而,这似乎是一种迂回的方式;使用字典来跟踪可变数组中不断变化的元素索引(特别是这是运行时错误的原因)。您确定要字典来跟踪数组中的索引和元素,而后者本质上是元素和相关索引的集合吗?
另一方面,如果你的谓词实际上更简单(只是删除字典中作为值存在的项目;不需要匹配跟踪的索引),你可以使用更简单的filter
方法:
array = array.filter { !dictionaryOfItems.values.contains($0) }
print(array) // ["Apple", "Orange", "lettuce", "Milk", "Tea"]
试试这个:
var array :[String] = ["Banana","Apple","Orange","Cucumber","lettuce","Milk","Tea"]
var dictionaryOfItems = [Int:String]()
dictionaryOfItems.updateValue("Banana", forKey: 0)
dictionaryOfItems.updateValue("Cucumber", forKey: 3)
var indexes = dictionaryOfItems.keys.sorted().reversed()
for index in indexes {
if array[index] == dictionaryOfItems[index] {
array.remove(at: index)
}
}