swift - 更改字典数组中的值 swift 5
问题描述
我正在使用 xcode 10.2 和 swift 5
我需要从“ arrNotificationList ”中的“ selected ” key = false/true更改所有值
// Create mutable array
var arrNotificationList = NSMutableArray()
// viewDidLoad method code
arrNotificationList.addObjects(from: [
["title":"Select All", "selected":true],
["title":"Match Reminder", "selected":false],
["title":"Wickets", "selected":false],
["title":"Half-Centure", "selected":false],
])
我尝试使用下面的代码,但原始数组“arrNotificationList”值没有改变。
arrNotificationList.forEach { value in
print("\(value)")
var dictNotification:[String:Any] = value as! [String : Any]
dictNotification["selected"] = sender.isOn // this is switch value which is selected by user on/off state
}
解决方案
要更改数组的元素,请使用map
function 而不是forEach
. 然后在 map 函数中返回更改更改的字典
var arrNotificationList = [[String:Any]]()
arrNotificationList = [["title":"Select All", "selected":true],
["title":"Match Reminder", "selected":false],
["title":"Wickets", "selected":false],
["title":"Half-Centure", "selected":false]]
arrNotificationList = arrNotificationList.map({
var dict = $0
dict["selected"] = sender.isOn
return dict
})
print(arrNotificationList)
推荐阅读
- docker - 通过 Docker 镜像使用 ownCloud 时文件存储在哪里?
- python - 如何使用 Python 数据类覆盖 OOP 继承中的属性
- unity3d - Unity Agora 屏幕共享视频质量模糊
- generics - 如何返回包装不同类型的“选项”向量?即`vec![选项
, 选项 ]` - node.js - 为什么 Next.js 在开发模式下运行时会多次重新初始化全局常量?
- sql - NOT 的意外行为
- rust - 为数字类型创建类型别名时不明确的关联类型
- git - git错误-致命:提取包:无效的索引包输出
- minizinc - 是什么导致“函数返回类型错误重载模棱两可”,我该如何解决?
- java - 为什么我的角色集会抛出 Unsupported UnsupportedOperationException?