swiftsortingarrayofarrays

How do I sort an array of an array in Swift 5


For example I have

[
["A",1]
["B",5]
["C",3]
]

How do i sort it so that it returns in Highest to lowest value B, C, A


Solution

  • You can do in following way:

    a.sort {
            return $0.last as! Int > $1.last as! Int
        }
    

    Don't forget to add additional checks while using this code, case where the last item is not an integer or there is an array not in the expected format. Otherwise, it will lead to a crash.