Last active
March 2, 2017 10:47
-
-
Save jmcd/79e554a72624db3ef937e5c4a15d02e8 to your computer and use it in GitHub Desktop.
Grouping an array by members in Swift
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 | |
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