Skip to content

Instantly share code, notes, and snippets.

@jmcd
Last active March 2, 2017 10:47
Show Gist options
  • Save jmcd/79e554a72624db3ef937e5c4a15d02e8 to your computer and use it in GitHub Desktop.
Save jmcd/79e554a72624db3ef937e5c4a15d02e8 to your computer and use it in GitHub Desktop.
Grouping an array by members in Swift
import Foundation
extension Array {
func group<Discrimininator>(by discriminator: (Element)->(Discrimininator)) -> [Discrimininator: [Element]] where Discrimininator: Hashable {
var result = [Discrimininator: [Element]]()
for element in self {
let key = discriminator(element)
var array = result[key] ?? [Element]()
array.append(element)
result[key] = array
}
return result
}
}
struct Name {
let first: String
let last: String
}
let names = [
Name(first: "Alice", last: "Smith"),
Name(first: "Bob", last: "Jones"),
Name(first: "Colin", last: "Smith"),
Name(first: "Alice", last: "Williams"),
]
print(names.group { $0.last })
// ["Jones": [Name(first: "Bob", last: "Jones")], "Williams": [Name(first: "Alice", last: "Williams")], "Smith": [Name(first: "Alice", last: "Smith"), Name(first: "Colin", last: "Smith")]]
print(names.group { $0.first })
// ["Bob": [Name(first: "Bob", last: "Jones")], "Alice": [Name(first: "Alice", last: "Smith"), Name(first: "Alice", last: "Williams")], "Colin": [Name(first: "Colin", last: "Smith")]]
print(names.group { $0.first.characters.count })
//[5: [Name(first: "Alice", last: "Smith"), Name(first: "Colin", last: "Smith"), Name(first: "Alice", last: "Williams")], 3: [Name(first: "Bob", last: "Jones")]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment