如何从字典数组中更改和删除Swift中的Element?

问题描述

我试图使用func deleteElement(id:Int)和remoteTodos.remove(at:id)从词典数组中删除一个元素,但没有任何反应。我也想更改字典中的值,例如“ key3”:Bool,但找不到任何匹配的样本

'''

var ArrayOfDictionaries: [[String : Any]] = [["id": 1,"key2": "text1","key3": false],["id": 2,"key2": "text2","key3": true]]

func deleteElement(with id: Int) {
        if ArrayOfDictionaries.count == 0 {
            print("list is empty")
        }
        ArrayOfDictionaries.remove(at: id)
    }

// remove Element with id: 2  
deleteElement(with id: 2) 

'''

解决方法

感谢@vacawama,您为我提供了很多帮助,代码应如下所示->更改值:let index = ArrayOfDictionaries.firstIndex(where: {$0["id"] as? Int == id}) { ArrayOfDictionaries[index]["key3"] = true }

并用于从数组中删除字典:let index = ArrayOfDictionaries.firstIndex(where: {$0["id"] as? Int == id}) { ArrayOfDictionaries.remove(at: index)}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...