Created
September 9, 2020 19:54
-
-
Save JanGorman/5d95b8a800f128cad25802c48893ba57 to your computer and use it in GitHub Desktop.
Nice trick to sort tuples by selected fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let foos: [(id: Int, bar: Int, baz: Int)] = [ | |
(100, 100, 100), | |
(2, 100, 100), | |
(3, 1000, 100), | |
(1, 101, 100), | |
(1, 100, 100), | |
] | |
// The comparison will first compare the .id fields and | |
// only if they are equal will it perform the comparison on the .bar field | |
let sorted = foos.sorted(by: { lhs, rhs in | |
(lhs.id, lhs.bar) < (rhs.id, rhs.bar) | |
}) | |
print(sorted) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment