Shreedhar Mathad Shreedhar Mathad - 6 months ago 131
Swift Question

How to sort Array of tuples (String,String,int)

I have an array of tuples. I want to sort the list by first element of tuples.

Example:

var names = [("C","MTS",4),("A","MTS",3),("M","SMTS",1),("N","LEAD",5)];


i want to sort them in the below order by first element of tuples

[("A","MTS",3),("C","MTS",4),("M","SMTS",1),("N","LEAD",5)];


Please Suggest.

Answer

Try this:

var names = [("C","MTS",4),("A","MTS",3),("M","SMTS",1),("N","LEAD",5)]
names.sortInPlace{ $0.0 < $1.0 }

// You can use this if it more clearly:
// names.sortInPlace { (name1: (String, String, Int), name2: (String, String, Int)) -> Bool in
       // return name1.0 < name2.0
//}

print(names)
//[("A", "MTS", 3), ("C", "MTS", 4), ("M", "SMTS", 1), ("N", "LEAD", 5)]
Comments