Created
June 9, 2018 17:47
-
-
Save gallaugher/ff5b6fb2b10417ddef02f62b27508b56 to your computer and use it in GitHub Desktop.
Sorting an array of structs on a single property
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
struct City { | |
var name: String | |
var rainyDays: Int | |
var rainTotal: Double | |
} | |
var cities: [City] = [] | |
cities.append(City(name: "Seattle", rainyDays: 149, rainTotal: 37.7)) | |
cities.append(City(name: "Phoenix", rainyDays: 30, rainTotal: 8.2)) | |
cities.append(City(name: "Chicago", rainyDays: 124, rainTotal: 36.9)) | |
cities.append(City(name: "Boston", rainyDays: 126, rainTotal: 43.8)) | |
cities.append(City(name: "Atlanta", rainyDays: 113, rainTotal: 49.7)) | |
cities.append(City(name: "Austin", rainyDays: 88, rainTotal: 34.2)) | |
// Note: the forEach method will print out each element in the array. You'll learn more about this in a later chapter | |
cities.sort(by: {$0.name < $1.name}) // Alphabetical | |
cities.forEach({print("\($0.name), \($0.rainyDays), \($0.rainTotal)")}) | |
print("") | |
cities.sort(by: {$0.rainyDays > $1.rainyDays}) // Most rainy days | |
cities.forEach({print("\($0.name), \($0.rainyDays), \($0.rainTotal)")}) | |
print("") | |
cities.sort(by: {$0.rainTotal < $1.rainTotal}) // Driest | |
cities.forEach({print("\($0.name), \($0.rainyDays), \($0.rainTotal)")}) | |
print("") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment