Created
June 9, 2018 16:50
-
-
Save gallaugher/e062492035420469d7a24521f152c96a to your computer and use it in GitHub Desktop.
Swift .sort(by:) and .sorted(by:) examples
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
var favoriteFoods = ["Pizza", "Apple Pie", "Sushi", "Bacon"] | |
let aToZFoods = favoriteFoods.sorted() | |
print(aToZFoods) // sorted array | |
print(favoriteFoods) // unchanged original | |
print("") | |
// .sorted() is the same as .sorted(by: <) | |
let alphabetizedFoods = favoriteFoods.sorted(by: <) | |
print(alphabetizedFoods) // sorted array | |
print(favoriteFoods) // unchanged original | |
print("") | |
// to reverse the order, use > | |
let zToAFoods = favoriteFoods.sorted(by: >) | |
print(zToAFoods) // sorted array | |
print(favoriteFoods) // unchanged original | |
print("") | |
// .sort(by:) works the same way, but it changes the order of the elements in the array. | |
favoriteFoods.sort() | |
print(favoriteFoods) // alphabetizes the array | |
favoriteFoods.sort(by:>) | |
print(favoriteFoods) // reverse alphabetical order the array | |
favoriteFoods.sort(by:<) // back to alphabetical order |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment