skip to Main Content

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


  1. 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.

    for key in orderToFollow
    {
        if let value = randomOrderDic[key]
        {
            // Do something with the value here
        }
    }
    

    That won’t get you any of the keys that do not appear in orderToFollow of course. To get those, you can use a filter

    let unorderedKeys = randomOrderDic.keys.filter { !orderToFollw.contains($0) }
    

    Apple’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.

    Login or Signup to reply.
  2. var dictionary = [ "benName": "abc","amount": 15.0,"toAccount": "123456","fromAccount": "789530"] as [String : Any]
    
    let array = ["fromAccount", "toAccount", "amount", "benName"]
    
    let sortedDictionary = Dictionary(uniqueKeysWithValues: dictionary.sorted { (first, second) -> Bool in
    let index1 = array.firstIndex(of: first.key) ?? 0
    let index2 = array.firstIndex(of: second.key) ?? 0
    return index1 < index2
    

    })

    print(sortedDictionary)
    

    //OutPut

    ["toAccount": "123456", "benName": "abc", "fromAccount": "789530", "amount": 15.0]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search