更改字典Swift 5数组中的值

时间:2019-05-23 09:10:01

标签: swift

我正在使用xcode 10.2和swift 5

我需要更改“ arrNotificationList ”中的“ 已选择”键= 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
        }

2 个答案:

答案 0 :(得分:1)

首先,使用NSMutableArray类型的Swift数组而不是使用[[String:Any]],即

var arrNotificationList = [[String:Any]]() //array of dictionaries

arrNotificationList.append(contentsOf: [
    ["title":"Select All", "selected":true],
    ["title":"Match Reminder", "selected":false],
    ["title":"Wickets", "selected":false],
    ["title":"Half-Centure", "selected":false],
    ])

现在,由于它是array of dictionary,并且dictionary是值类型,所以在foreach loop中对其所做的任何更改都不会反映在原始dictionary中。

使用 map(_:) selected = sender.isOn数组中的所有dictionaries使用arrNotificationList获取一个新数组。

        arrNotificationList = arrNotificationList.map {
            ["title": $0["title"], "selected": sender.isOn]
        }

答案 1 :(得分:1)

要更改数组的元素,请使用map函数而不是forEach。然后在地图功能中返回更改更改的字典

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)