所以,我有一个包含这样的字符串数组的字典:
vld1.32 {d0-d1}, [r0]
现在我必须能够从数组中删除一个值。 例: 我想删除“dev4”,无论它是在“Section1”还是“Section2”中。
我将如何做到这一点?
答案 0 :(得分:3)
使用 Swift4 ,可以选择将地图应用于字典的值:
var dict = ["Section1": ["dev1", "dev2"], "Section2": ["dev3", "dev4"]]
dict = dict.mapValues{ $0.filter{ $0 != "dev4" } }
给出了结果:
dict // -> ["Section1": ["dev1", "dev2"], "Section2": ["dev3"]]
答案 1 :(得分:1)
for key in dict.keys {
dict[key] = dict[key]!.filter({ $0 != "dev4"})
}
答案 2 :(得分:0)
一些示例代码:
func removeValue(value: String, fromDict dict: [String: [String]]) -> [String: [String]] {
var out = [String: [String]]()
for entry in dict {
out[entry.key] = entry.value.filter({
$0 != value
})
}
return out
}
var dict = ["Section1": ["dev1", "dev2"], "Section2": ["dev3", "dev4"]]
let new = removeValue(value: "dev4", fromDict: dict)
答案 3 :(得分:0)
迷你版:
dict.forEach({ (k, v) in dict[k] = v.filter({ $0 != "dev4" }) })
print(dict) // ["Section1": ["dev1", "dev2"], "Section2": ["dev3"]]