Skip to content

Instantly share code, notes, and snippets.

@gallaugher
Created June 9, 2018 16:50
Show Gist options
  • Save gallaugher/e062492035420469d7a24521f152c96a to your computer and use it in GitHub Desktop.
Save gallaugher/e062492035420469d7a24521f152c96a to your computer and use it in GitHub Desktop.
Swift .sort(by:) and .sorted(by:) examples
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