Created
December 12, 2017 09:47
-
-
Save Marcocanc/e3ea8b221d02d1b452d50dd07f0bb867 to your computer and use it in GitHub Desktop.
Swift 4 Keypath for grouping sequences
This file contains hidden or 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 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