TL ; DR:
Give sorted a closure. It gets two items and returns true when the first one goes first. For two rules, give the closure a body with an if.
let nums = [25, 13, 5, 41, 33]
let byLastDigit = nums.sorted { a, b in
if a % 10 != b % 10 {
return a % 10 < b % 10
}
return a < b
}
// [41, 13, 33, 5, 25]
let scores = [70, 95, 82]
let highFirst = scores.sorted { $0 > $1 }
// [95, 82, 70]
Full lesson:
In Closures & Sorting you passed a closure to sorted. A closure is a small function without a name. It gets two items. It returns true when the first must go before the second.
- High to low:
sorted { $0 > $1 }. - Shortest first:
sorted { $0.count < $1.count }.
Sometimes one rule is not enough. Two numbers with the same last digit need a second rule, like small to large.
A closure with two rules needs more than one line. Name its two items with a, b in at the start. Names read better than $0 and $1 here.
Check the first rule. Use the second one only on a tie, as the if above does. Above, the first rule compares the last digits, a % 10 and b % 10.
Comparing two strings with < puts them from A to Z.
Remember the difference. The sorted method makes a new array. The sort method sorts a var array itself.
Your task
A pet shop sells toys. Their prices are in prices. Make an array named highFirst with the prices from high to low.
The shop's pets are in names. Make an array named byLastLetter with the names sorted by their last letter, in alphabetical order. Names with the same last letter go from A to Z.
The code already prints both, one item per line.
Expected output:
30
12
8
5
Bella
Luna
Bo
Coco
Max
RexFree plan: 30 tutor messages. PRO is unlimited.
