Skip to content

Instantly share code, notes, and snippets.

@ppth0608
Last active July 2, 2019 15:59
Show Gist options
  • Save ppth0608/c255422a3ff80b64bf7646c9b95d2e7c to your computer and use it in GitHub Desktop.
Save ppth0608/c255422a3ff80b64bf7646c9b95d2e7c to your computer and use it in GitHub Desktop.
Array to Dictionaty group by value
struct Person: CustomDebugStringConvertible {
var name: String
var age: Int
var debugDescription: String {
return "\(name)(\(age))"
}
}
let persons = [
Person(name: "Park", age: 20),
Person(name: "Kim", age: 22),
Person(name: "Lee", age: 20),
Person(name: "Choi", age: 21),
Person(name: "Jo", age: 21),
Person(name: "Jo", age: 24),
]
let groupByAge = Dictionary(grouping: persons) { $0.age }
print(groupByAge)
// [24: [Jo(24)],
// 20: [Park(20), Lee(20)],
// 22: [Kim(22)],
// 21: [Choi(21), Jo(21)]]
let groupByName = Dictionary(grouping: persons) { $0.name }
print(groupByName)
// ["Kim": [Kim(22)],
// "Park": [Park(20)],
// "Jo": [Jo(21), Jo(24)],
// "Lee": [Lee(20)],
// "Choi": [Choi(21)]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment