Created
September 29, 2023 19:28
-
-
Save timsneath/0a22ea73296f781b1c2070a7688c6e50 to your computer and use it in GitHub Desktop.
Sorting in reverse, using an idiomatic Swift approach.
This file contains hidden or 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'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