dict = ["H": ["hello", "hi"], "J": ["joker"]]
如何从这样的词典中删除“hi”它看起来像
dict = ["H": ["hello"], "J": ["joker"]]
我使用了吗? dict.removeAtIndex(),如果是这样的话?
答案 0 :(得分:2)
试试这个:
let dict = ["H": ["hello", "hi"], "J": ["joker"]]
let dict2 = dict.map { (key,value) -> [String:[String]] in
let v = value.filter({$0 != "hi"})
return [key:v]
}
print(dict2) //[["H": ["hello"]], ["J": ["joker"]]]
答案 1 :(得分:1)
您可以使用indexOf,如下所示:
var dict = ["H": ["hello", "hi"], "J": ["joker"]]
if let index = dict["H"]?.indexOf("hi") {
dict["H"]?.removeAtIndex(index)
}
dict // ["H": ["hello"], "J": ["joker"]]
Xcode 8 beta•Swift 3将是:
var dict = ["H": ["hello", "hi"], "J": ["joker"]]
if let index = dict["H"]?.index(of: "hi") {
dict["H"]?.remove(at: index)
}
dict