Skip to content

Instantly share code, notes, and snippets.

@jcampbell05
Last active August 19, 2020 23:10
Show Gist options
  • Save jcampbell05/b29bc8d7d10d2e869cf2732871c4ecbf to your computer and use it in GitHub Desktop.
Save jcampbell05/b29bc8d7d10d2e869cf2732871c4ecbf to your computer and use it in GitHub Desktop.
import UIKit
protocol Sortable {}
extension Sequence where Element: Sortable {
func sorted<Q>(byKeys keys: [KeyPath<Element, Q>]) -> [Element] where Q: Hashable & Comparable {
guard let key = keys.first else {
return self as! [Self.Element]
}
var buckets: [Q: [Element]] = Dictionary(grouping: self) { element in
return element[keyPath: key]
}
let indexs = buckets.keys.sorted()
buckets.forEach { index, body in
var remainingKeys = keys
remainingKeys.removeFirst()
let bucket = buckets[index]
buckets[index] = bucket!.sorted(byKeys: remainingKeys)
}
let values = indexs.map { buckets[$0]! }
let result = values.reduce([], +)
return result
}
}
struct Person {
let firstName: String
let lastName: String
}
extension Person: Sortable {}
let people = [
Person(firstName: "James", lastName: "Campbell"),
Person(firstName: "Bruce", lastName: "Wayne"),
Person(firstName: "Bob", lastName: "Campbell")
]
let sorted = people.sorted(byKeys:[\.lastName, \.firstName])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment