Skip to content

Instantly share code, notes, and snippets.

@timsneath
Created September 29, 2023 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timsneath/0a22ea73296f781b1c2070a7688c6e50 to your computer and use it in GitHub Desktop.
Save timsneath/0a22ea73296f781b1c2070a7688c6e50 to your computer and use it in GitHub Desktop.
Sorting in reverse, using an idiomatic Swift approach.
/// Let's sort this array in reverse alphabetical order. Credit to @JoaquinAlori at @tryolabs for the idea.
let names = ["Mavericks", "Yosemite", "El Capitan", "Sierra", "High Sierra",
"Mojave", "Catalina", "Big Sur", "Monterey", "Ventura", "Sonoma"]
var reversedNames : [String]
/// ✅ Sort method returns true when the first element should be ordered before the second.
func backward(_ a: String, _ b: String) -> Bool {
return a > b
}
reversedNames = names.sorted(by: backward)
/// 👍 We can simplify this with a closure. `in` separates the arguments from the body.
reversedNames = names.sorted(by: { a, b in return a > b } )
/// 🤩 In Swift, single expression closures implicitly return their result, so we don't need the `return`:
reversedNames = names.sorted(by: { a, b in a > b } )
/// 🔥 Swift also has implicitly named positional parameters, so we can replace `a` and `b` with `$0`
/// and `$1`, representing the zeroth and first parameter.
reversedNames = names.sorted(by: { $0 > $1 } )
/// 🙀 But we can do better yet. In Swift, an operator is just another function, so we can simply write:
reversedNames = names.sorted(by: >)
/// Here are the first five names, sorted in reversed order:
print(reversedNames[0..<5])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment