Skip to content

Instantly share code, notes, and snippets.

@JanGorman
Created June 16, 2014 12:51
Show Gist options
  • Save JanGorman/65bbacea2e97ab2da250 to your computer and use it in GitHub Desktop.
Save JanGorman/65bbacea2e97ab2da250 to your computer and use it in GitHub Desktop.
Readable Sorting
class Person {
var age: Int
var name: String
init(age: Int, name: String) {
self.age = age
self.name = name
}
enum Order {
case ByAge
case ByName
func sorter() -> ((Person, Person) -> Bool) {
switch self {
case .ByAge:
return {(lhs: Person, rhs: Person) -> Bool in
return rhs.age > lhs.age
}
case .ByName:
return {(lhs: Person, rhs: Person) -> Bool in
return rhs.name > lhs.name
}
}
}
}
}
let firstChild = Person(age: 20, name: "Foo")
let secondChild = Person(age: 19, name: "Bar")
sort([firstChild, secondChild], Person.Order.ByAge.sorter())
sort([firstChild, secondChild], Person.Order.ByName.sorter())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment