更改字典 swift 数组中的值 5.

  • 本文关键字:数组 字典 swift swift
  • 更新时间 :
  • 英文 :


我正在使用 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数组中所有dictionariesselected = sender.isOn

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

最新更新