Quantcast
Channel: User Burhanuddin Sunelwala - Stack Overflow
Viewing all articles
Browse latest Browse all 36

Answer by Burhanuddin Sunelwala for Swift 3: Array to Dictionary?

$
0
0

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]] 

source

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.)


Viewing all articles
Browse latest Browse all 36

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>