首页 > 解决方案 > 如何仅更改字典键?无需快速更改值

问题描述

我有这样的数组。

var Array = [Int:[String:Any]]()

我只是更新值

 let updateValue = ["Name":tripName!,"date":firstDate,"year":year,"startData":startDateValue,"endDate":endDateValue,"countryName":countrname!,"totelBudjet":totelBudjet,"backgroundImage":arrImages[randomItem],"code":getAddtripeAttibutes.code,"countryIcon":countryIcon] as [String : Any]

 Array.updateValue(updateValue, forKey: tripId)

 tripId = tripId + 1

我们有更多的数组数据,如下所述

行程键如:

[0] [1] [2]

[0: ["year": "2019", "tripName": "Test", "backgroundImage": "Europe_Trip", "code": "DZD", "startData": 2019-05-30 10:14:11 +0000, "date": "May 30 - May 31", "endDate": 2019-05-31 10:14:11 +0000, "totelBudjet": "5000 DZD", "countryIcon": "dz", "countryName": "Algeria"], 1: ["date": "May 30 - May 31", "backgroundImage": "Europe_Trip", "endDate": 2019-05-31 10:14:43 +0000, "code": "DZD", "countryName": "Algeria", "tripName": "Gg", "countryIcon": "dz", "totelBudjet": "500 DZD", "startData": 2019-05-30 10:14:43 +0000, "year": "2019"], 2: ["year": "2019", "backgroundImage": "Asia_Trip", "endDate": 2019-05-31 10:15:00 +0000, "countryIcon": "al", "totelBudjet": "5800 ALL", "code": "ALL", "tripName": "Bb", "countryName": "Albania", "date": "May 30 - May 31", "startData": 2019-05-30 10:15:00 +0000]]

我已经用上述数据更新了表格视图

在我删除一个数组 [1] 之后,它看起来像:这个

[0] [2]

 [0: ["year": "2019", "tripName": "Test", "backgroundImage": "Europe_Trip", "code": "DZD", "startData": 2019-05-30 10:14:11 +0000, "date": "May 30 - May 31", "endDate": 2019-05-31 10:14:11 +0000, "totelBudjet": "5000 DZD", "countryIcon": "dz", "countryName": "Algeria"], 2: ["year": "2019", "backgroundImage": "Asia_Trip", "endDate": 2019-05-31 10:15:00 +0000, "countryIcon": "al", "totelBudjet": "5800 ALL", "code": "ALL", "tripName": "Bb", "countryName": "Albania", "date": "May 30 - May 31", "startData": 2019-05-30 10:15:00 +0000]]

但我想将密钥更新为 [0][1] 而不是 [0][2]

有人可以帮我吗?

标签: iosarraysswiftsortingdictionary

解决方案


您为什么要尝试使用字典来模拟数组?

如果你有这样的数组。

var array: [[String: Any]] = [["year": "2019"], ["year": "2020"], ["year": "2021"]] // Minimalistic example array

您可以删除该特定位置的值,它会为您提供当前所需的内容。

array.remove(at: 1)
print(array[1])

[“年份”:“2021”]


注意- 您的数据看起来像 JSON 响应。因此,您可以在评论中使用@Kamran的建议,并使用Trip符合的结构Decodable并直接将您的数据作为 s 数组获取Trip。但是,如果您的 JSON 使用键 0、1、2... 格式化,那么您的 JSON 真的很糟糕,如果可以的话,您应该更改它。如果不能,则必须将字典字典更改为字典数组或更好的结构数组。


推荐阅读