Sorting Multi Dimensional Array (Swift 3)

Hello all, 

This one I’ve found specially useful when working with Core Data fetched arrays. 

Let’s say that we want to sort the result of a fetch request based on the value of the field “gold”, we would therefore do the following:

let dwarfGoldBags = … //Contains the result of a fetch request with one of the fields named “gold” and being an integer.


We will now proceed to sort the array and store it in sortedGoldArray:

let sortedGoldArray = dwarfGoldBags.sorted { ($0.goldas Int) > ($1.goldas Int) } 


If instead of core data you have a multi-dimensional array it would be as easy as:

let sortArray = originalArray.sorted { ($0.[0] as Int) > ($1.[0] as Int) } 


In this case we’re comparing the values stored in the first value of the subArrays. 

Questions / comments? I’m at @MarcMasVi