On Swift 4, you can achieve this by using Dictionary'sgrouping:by:
initializer
For ex: You have class named A
class A { var name: String init(name: String) { self.name = name } // . // . // . // other declations and implementions}
Next, you have an array of objects of type A
let a1 = A(name: "Joy")let a2 = A(name: "Ben")let a3 = A(name: "Boy")let a4 = A(name: "Toy")let a5 = A(name: "Tim")let array = [a1, a2, a3, a4, a5]
Let's say you want to create a Dictionary by grouping all the names by their first letter. You use Swifts Dictionary(grouping:by:)
to achieve this
let dictionary = Dictionary(grouping: array, by: { $0.name.first! })// this will give you a dictionary// ["J": [a1], "B": [a2, a3], "T": [a4, a5]]
Note however that the resulting Dictionary "dictionary" is of type
[String : [A]]
it is not of type
[String : A]
as you may expect. (Use #uniqueKeysWithValues
to achieve the latter.)