Skip to content

Instantly share code, notes, and snippets.

@Marcocanc
Created December 12, 2017 09:47
Show Gist options
  • Save Marcocanc/e3ea8b221d02d1b452d50dd07f0bb867 to your computer and use it in GitHub Desktop.
Save Marcocanc/e3ea8b221d02d1b452d50dd07f0bb867 to your computer and use it in GitHub Desktop.
Swift 4 Keypath for grouping sequences
import Foundation
internal extension Sequence {
func grouped<T>(by keyPath: KeyPath<Element, T>) -> [T: [Element]] {
var groups = [T: [Element]]()
for element in self {
let key = element[keyPath: keyPath]
if !groups.keys.contains(key) {
groups[key] = [Element]()
}
groups[key]?.append(element)
}
return groups
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment