Swift Program to Sort a Dictionary By Values

Swift supports a sorted() method to sort all the elements present in the given dictionary. This method sorts the key-value pairs of the dictionary according to the values.


func sorted(by:)

Here, the value of by parameters are −

  • Greater than(>) − To sort the elements into descending order.

  • Less than(<) − To sort the elements into ascending order.

  • Closure − Sort the elements according to the given closure.


  • Step 1 − Create a dictionary with key-value pairs.

  • Step 2 − Display the original dictionary.

  • Step 3 − Now use the sorted() function to sort the key-value pairs according to their values.

  • Step 4 − Display the final output.


In the following Swift program, we are going to sort the dictionary by values. So we will create a dictionary. Then pass this closure ({ $0.value < $1.value }) in the sorted(by:) function to sort the elements of the dictionary according to the value and display the final result. Here $0 and $1 represent the first and second parameters passed into the closure.

import Foundation
import Glibc

let myDict = ["name": "Sona", "company": "MOKA.PVT", "city": "New Delhi"]

print("Original dictionary:", myDict)

let Sdict = myDict.sorted(by: { $0.value < $1.value })

print("Sorted dictionary:", Sdict)


Original dictionary: ["name": "Sona", "company": "MOKA.PVT", "city": "New Delhi"]
Sorted dictionary: [(key: "company", value: "MOKA.PVT"), (key: "city", value: "New Delhi"), (key: "name", value: "Sona")]


So this is how we can sort dictionaries by values. The sorted() method returns accurate results. Also, it does not modify the original dictionary instead it creates a new dictionary which contains the result. The complexity of the sorted(by:) method is O(n log n) where n is the length of the dictionary.

Updated on: 09-May-2023


Kickstart Your Career

Get certified by completing the course

Get Started