Dictionary [String: String] keys order changed when converted to array swift

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

I have a dictionary like below,

var dataSource: [String: String] = ["FirstName": "Austin",                                     "ListName": "Michael",                                     "Address": "Street Address",                                     "City": "Chennai"]

I want to populate these values in a UITableView, so I tried to get all the keys from Dictionary to an Array like below,

let dataArray = Array(dataSource.keys)

I got the output as [String] like,

["LastName", "FirstName", "City", "Address"]

The problem is, the order of the keys has changed, I want the array in the same order as dictionary has.

Can you anyone help?

回答1:

Use plain dictionary as tableview datasource is bad idea.

However Dictionary can not be sorted. So it doesn't matter in what order you add your keys-values to the dictionary.

If you need sorted then use array of dictionary instead.

You should use models instead of plain dictionary that is easy to maintain :]

like

struct User {      var firstName:String?     var lastName:String?     var address:String?     var city:String? }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!