编辑: 我想删除结构类型的数组列表中的元素之一
struct Folder {
let name:String
let menu:[String:String]
}
我有一个变量
section = Folder
我想检查菜单中是否有任何值[String:String]是否包含特定值,然后将该元素删除
section.menu = ["hello" : "a","b","c"]
if there any value of hello == a {
remove it out
}
最后
section.menu = ["hello" : "b","c"]
答案 0 :(得分:0)
因此,首先您需要使menu
成为实际变量而不是常量,并且它必须是从Strings到String Array的字典。
然后,您可以通过获取它们的索引并调用remove
来轻松地从数组中删除条目:
struct Folder {
let name:String
var menu: [String: [String]]
}
var section = Folder(name: "foo", menu: [ "hello": ["a", "b", "c"]])
if let index = section.menu["hello"]?.firstIndex(of: "a") {
section.menu["hello"]?.remove(at: index)
}
print(section.menu) // ["hello": ["b", "c"]]
答案 1 :(得分:0)
您可以创建mutating
之类的removeMenu(forValue value: String)
函数
struct Folder {
let name:String
var menu:[String:String]
mutating func removeMenu(forValue value: String) {
menu = menu.filter({ $0.value != value})
}
}
var section = Folder(name: "FolderName", menu: ["k1": "keyValue1", "k2": "keyValue2"])
section.removeMenu(forValue: "keyValue1")
print(section)
输出:
//Folder(name: "FolderName", menu: ["k2": "keyValue2"])