Skip to content

Instantly share code, notes, and snippets.

@bmichotte
Created October 26, 2017 16:56
Show Gist options
  • Save bmichotte/0d0c487ff61e74bc34ca049bcefd3b96 to your computer and use it in GitHub Desktop.
Save bmichotte/0d0c487ff61e74bc34ca049bcefd3b96 to your computer and use it in GitHub Desktop.
struct A { let a: String }
let array = [A(a: "b"), A(a: "C"), A(a: "b")]
let dictionary = Dictionary(grouping: array) { $0.a }
dictionary
extension Array {
func group<K: Hashable, Element>(_ fn: (Element) -> K) -> Dictionary<K, [Element]> {
return Dictionary<K, [Element]>(grouping: self, by: fn)
}
}
let dictionary2 = array.group { $0.a }
dictionary2
@JohnSundell
Copy link

Remove Element as a generic type local to the function (since that override's Array's associated Element type). So replace line 7 with this:

func group<K: Hashable>(_ fn: (Element) -> K) -> Dictionary<K, [Element]> {

And it'll work 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment