我正在使用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
}
答案 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)