Here's an example. Say you gather your family around the dining room table. You dump a box of fruit on the table, and you ask each person to "sort" the fruit. This may not make sense to everyone, as there is no prescribed way to "sort" fruit.
Instead, you give each person a sorting rule.
- You ask Agnetha to sort the fruit alphabetically, by color.
- Bjorn sorts the fruit by size: longest to shortest.
- Anni-Frid sorts the fruit by taste: bland, sweet, then sour.
- Benny sorts the fruit by weight: lightest to heaviest.
Each is performing a sort function, but you had to specify the sort rules.
When comparing two different fruits, what is the rule to determine weight? What is the rule for sorting color?
This is the function of the closure you supply to the sorted(by:) method.
Swift will give the closure two of your fruits (say the banana and the peach. Or the pomegranite and the plum.) It doesn't matter which two fruits it receives, you need to provide the rules to determine if fruit #1 is ordered before fruit #2.
The beautiful thing about closures is you can easily change the sorting rules based on your needs!
In this example below. Think through what you are asking Bjorn to do?
You give him two names ("Piper and Gloria", or "Tiffany and Suzanne"). But no matter what the names are, you're just saying returning true. This essentially tells the sort routine that name1 will always be sorted before name2. You're not comparing anything.
To make this more clear, you might want to add a print statement inside and watch the console.
let sort1 = team.sorted { name1, name2 in
print("\(name1) is before \(name2)") // watch the console as Swift sends values to be compared.
return true // not really a useful sorting rule, is it?
}
print(sort1)
// Prints - ["Tasha", "Tiffany", "Piper", "Suzanne", "Gloria"]
- Suzanne is before Gloria
- Piper is before Gloria
- Piper is before Suzanne
- Tiffany is before Gloria
- Tiffany is before Suzanne
- Tiffany is before Piper
- Tasha is before Gloria
- Tasha is before Suzanne
- Tasha is before Piper
- Tasha is before Tiffany
Here's a second example with some better sorting logic. Sort the list of names by how many letters are in each name.
Run this in Playgrounds. Do you see how the sortby rule is applied?
let team = ["Gloria", "Ed", "Paul", "Piper", "Tiffany", "Tasha"]
let sortByLength = team.sorted { name1, name2 in
if name1.count >= name2.count { // this rule makes a bit more sense.
print ("\(name1) has more letters than \(name2)")
return true
} else {
print ("\(name1) has fewer letters than \(name2)")
return false
}
}
print(sortByLength)