首页 > 解决方案 > 更改字典数组中的值 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
        }

标签: swift

解决方案


要更改数组的元素,请使用mapfunction 而不是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)

推荐阅读