Reputation: 5213
I am using xcode 10.2 and swift 5
I need to change all values from "selected" key = false/true in "arrNotificationList"
// 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],
])
I have try with below code but original array "arrNotificationList" value not changed.
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
}
Upvotes: 1
Views: 5659
Reputation: 24341
First of all, instead of using NSMutableArray
, use Swift
array of type [[String:Any]]
, i.e.
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],
])
Now, since it is an array of dictionary
, and dictionary
is a value type, so any changes done to it in foreach loop
won't reflect in the original dictionary
.
Use map(_:)
to get a new array with selected = sender.isOn
for all the dictionaries
in arrNotificationList
array.
arrNotificationList = arrNotificationList.map {
["title": $0["title"], "selected": sender.isOn]
}
Upvotes: 1
Reputation: 15748
To change elements of an array use map
function instead of forEach
. Then return change changed dictionary in map function
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)
Upvotes: 4