Skip to content

Instantly share code, notes, and snippets.

@loganwright
Created October 22, 2015 20:16
Show Gist options
  • Save loganwright/d4ecf3d47748c54255a0 to your computer and use it in GitHub Desktop.
Save loganwright/d4ecf3d47748c54255a0 to your computer and use it in GitHub Desktop.
Sort Priorities in Swift
enum SortOrder {
case Ascending, Descending, Same
}
extension Array {
typealias Sorter = (Element, Element) -> SortOrder
func sortWithPriorities(sorters: Sorter...) -> Array {
return sort { (left, right) -> Bool in
for sorter in sorters {
switch sorter(left, right) {
case .Ascending:
return true
case .Descending:
return false
case .Same:
continue
}
}
return true
}
}
}
struct Human {
let name: String
let age: Int
}
func humanAgeSorter(left: Human, right: Human) -> SortOrder {
if left.age < right.age {
return .Ascending
} else if left.age > right.age {
return .Descending
} else {
return .Same
}
}
func humanNameSorter(left: Human, right: Human) -> SortOrder {
if left.name < right.name {
return .Ascending
} else if left.name > right.name {
return .Descending
} else {
return .Same
}
}
let humans: [Human] = [
("Joe", 20),
("Jane", 20),
("Abe", 31),
("Zorro", 15),
("Abbot", 15)
]
.map { Human(name: $0.0, age: $0.1) }
humans.sortWithPriorities(humanAgeSorter, humanNameSorter)
@loganwright
Copy link
Author

Will give following output:

[Human(name: "Abbot", age: 15), Human(name: "Zorro", age: 15), Human(name: "Jane", age: 20), Human(name: "Joe", age: 20), Human(name: "Abe", age: 31)]

For the record, this may not be the most efficient or best solution. If by some reason you happen to come across this and have suggestions/improvements, please offer them!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment