Created
October 22, 2015 20:16
-
-
Save loganwright/d4ecf3d47748c54255a0 to your computer and use it in GitHub Desktop.
Sort Priorities in Swift
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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Will give following output:
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!