Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize dictionary from array with Swift 3

Tags:

swift

Is there a more simple/efficient way to initialize a dictionary from an array in Swift 3?

for object in array {
    dict[object.id] = object
}

Nothing wrong with the above but I was wondering if you could use map/reduce/etc to do this with slightly less code.

like image 329
Marcus Leon Avatar asked Dec 07 '25 08:12

Marcus Leon


1 Answers

array.forEach({ object in
    dict[object.id] = object
})

or shorter:

array.forEach({ dict[$0.id] = $0 })
like image 153
Danut Pralea Avatar answered Dec 08 '25 23:12

Danut Pralea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!