Skip to content

Instantly share code, notes, and snippets.

@JanGorman
Created September 9, 2020 19:54
Show Gist options
  • Save JanGorman/5d95b8a800f128cad25802c48893ba57 to your computer and use it in GitHub Desktop.
Save JanGorman/5d95b8a800f128cad25802c48893ba57 to your computer and use it in GitHub Desktop.
Nice trick to sort tuples by selected fields
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