Skip to content

Instantly share code, notes, and snippets.

@d6u
Last active August 29, 2015 14:24
Show Gist options
  • Select an option

  • Save d6u/5ef970186f5e46d90bee to your computer and use it in GitHub Desktop.

Select an option

Save d6u/5ef970186f5e46d90bee to your computer and use it in GitHub Desktop.
struct Entity {
let name: String
let age: Int
}
enum SortResult {
case LeftFirst
case RightFirst
case Same
}
func multiSort<T>(array: [T], sorter: [(T, T) -> SortResult]) -> [T] {
return sorted(array, { (a, b) -> Bool in
var r: SortResult?
for cb in sorter {
r = cb(a, b)
if r != .Same {
break
}
}
return r == .LeftFirst ? true : false
})
}
var arr = [
Entity(name: "b", age: 18),
Entity(name: "a", age: 18),
Entity(name: "c", age: 20),
Entity(name: "d", age: 30)
]
var r = multiSort(arr, [
{(a, b) in a.age == b.age ? .Same : (a.age < b.age ? .LeftFirst : .RightFirst)},
{(a, b) in a.name < b.name ? .LeftFirst : .RightFirst},
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment