Sort Array of Dictionaries by Key Value

Probably something like this, using sort:

let sortedArray = itemsArray.sort { $0["itemName"] < $1["itemName"] }

where “$0” and “$1” represent respectively, in the array, each dictionary and its successor.


If the compiler complains about the types because it doesn’t know that the value for this key is a String, you can cast like this (as said by @Cristik in the comments):

let sortedArray = itemsArray.sort { ($0["itemName"] as? String) < ($1["itemName"] as? String) }

Leave a Comment