I have an array like this :
var orderToFollow:[String] = ["fromAccount", "toAccount", "amount", "benName"]
and a dictionary like this :
var randomOrderDic = [
"benName": "abc",
"amount": 15.0,
"toAccount": "123456",
"fromAccount": "789530"
]
How can i sort the randomOrderDic to something like:
[
"fromAccount": "789530",
"toAccount": "123456",
"amount": 15.0,
"benName": "abc"
]
P.S. I’m new to coding so i don’t know how to solve this. Any help is much appreciated
2
Answers
Dictionaries are unordered by design. If you want to retrieve values in a certain order, you can iterate through an array of the keys in the order you want and retrieve each value.
That won’t get you any of the keys that do not appear in
orderToFollow
of course. To get those, you can use a filterApple’s Swift collections package does offer an
OrderedDictionary
type, but it is probably better to get used to the fact that dictionary keys are unordered. There aren’t may use-cases where you do need an ordering.})
//OutPut