Reputation: 490
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?
Upvotes: 0
Views: 521
Reputation: 16446
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?
}
Upvotes: 3