ios - 如何从字典中删除指定键的一对?
问题描述
我想写一个带参数的函数,用于与字典的键进行比较。该函数迭代一个集合并检查 case 是否具有与此键的对。如果有,我想删除那对,将另一对留在这种情况下,然后继续下一个情况。
我创建了一个函数 filterAndExtract()。然而它只是迭代并且什么都不做。在每种情况下比较(Bool)参数和键时,它不能按预期工作。我想知道如何识别一对中的密钥,以便我可以对集合中的案例做一些事情。提前致谢!
enum Tags: String {
case one = "One"
case two = "Two"
case three = "Three"
}
struct Example {
var title: String
var pair: [Tags: String]
}
let cases = [
Example(title: "Random example One", pair: [Tags.one: "First preview", Tags.two: "Second preview"]),
Example(title: "Random example Two", pair: [Tags.two: "Thrid preview", Tags.three: "Forth preview"]),
Example(title: "Random example Three", pair: [Tags.three: "Fifth preview", Tags.one: "Sixth preview"])
]
func filterAndExtract(collection: [Example], tag: Tags) {
for var item in collection {
let keys = item.pair.keys
for key in keys {
if key == tag {
item.pair.removeValue(forKey: key)
}
}
}
for i in collection {
print("\(i.title) and \(i.pair.values) \nNEXT TURN--------------------------------------------------\n")
}
}
//Results:
//Random example One and ["Second preview", "First preview"]
//NEXT TURN--------------------------------------------------
//Random example Two and ["Thrid preview", "Forth preview"]
//NEXT TURN--------------------------------------------------
//Random example Three and ["Fifth preview", "Sixth preview"]
//NEXT TURN--------------------------------------------------
//Solution (how I want it to look at the end):
for var i in cases {
i.pair.removeValue(forKey: .three)
print("\(i.title) and \(i.pair.values) \nNEXT TURN--------------------------------------------------\n")
}
//Random example One and ["Second preview", "First preview"]
//NEXT TURN--------------------------------------------------
//Random example Two and ["Thrid preview"]
//NEXT TURN--------------------------------------------------
//Random example Three and ["Sixth preview"]
//NEXT TURN--------------------------------------------------
解决方案
Swift 集合是值类型。每当您将集合分配给变量时,您都会获得该对象的副本。
要修改参数collections
,您必须使其可变,并且必须直接在内部修改值collections
。
func filterAndExtract(collection: [Example], tag: Tags) {
var collection = collection
for (index, item) in collection.enumerated() {
let keys = item.pair.keys
for key in keys {
if key == tag {
collection[index].pair.removeValue(forKey: key)
}
}
}
for i in collection {
print("\(i.title) and \(i.pair.values) \nNEXT TURN--------------------------------------------------\n")
}
}
推荐阅读
- serialization - oneway IEnumerable 处理
- javascript - 如何通过使用 jQuery Ajax 调用来防止会话超时?
- json - 解析字典行为奇怪
- java - 如何修复 com.android.volley.ParseError: org.json.JSONExeption: Value
我有一个 listview 的自定义适配器,我想从数据库中获取项目列表并使用 json 从 php 构建 CustomArrayAdapter,但问题是我从
- c# - 将表达式树转换为字典
- performance - 过滤的最佳解决方案
- javascript - 从远程 js 文件中读取导出的变量
- rust - 如何在容器中存储和检索对象,这些对象自身和容器发生变异
- javascript - 使用 react-web-tabs,有没有办法通过点击切换标签并导航到散列 ID?
- node.js - NodeJs 在 Create React App 中导入文件