我正在使用 xcode 10.2 和 swift 5
我需要更改">已选择"键 = 在">arr通知列表"中的错误/真的所有值
// 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
请使用函数而不是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)
首先,不要使用NSMutableArray
,而是使用[[String:Any]]
类型的数组Swift
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(_:)
获取一个新数组,其中包含arrNotificationList
数组中所有dictionaries
的selected = sender.isOn
。
arrNotificationList = arrNotificationList.map {
["title": $0["title"], "selected": sender.isOn]
}