Last active
August 19, 2020 23:10
-
-
Save jcampbell05/b29bc8d7d10d2e869cf2732871c4ecbf to your computer and use it in GitHub Desktop.
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
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