在 swift 中删除结构数组中的元素



>编辑: 我想删除结构类型的数组列表中的一个元素

struct Folder {
let name:String
let menu:[String:String]
}

我有一个变量

section = Folder

我想检查菜单[字符串:字符串]中是否有任何值是否包含特定值,并将该元素删除

section.menu = ["hello" : "a","b","c"]
if there any value of hello == a {
remove it out
}

在最后

section.menu = ["hello" : "b","c"]

你可以像这样创建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"])

所以首先你需要使menu成为一个实际的变量而不是一个常量,它需要是一个字符串到字符串数组的字典。

然后,您可以通过获取条目的索引并调用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"]]

最新更新