Swift Dictionary: Get values as array

Stuart Source

I have a dictionary containing UIColor objects hashed by an enum value, ColorScheme:

var colorsForColorScheme: [ColorScheme : UIColor] = ...

I would like to be able to extract an array of all the colors (the values) contained by this dictionary. I thought I could use the values property, as is used when iterating over dictionary values (for value in dictionary.values {...}), but this returns an error:

let colors: [UIColor] = colorsForColorSchemes.values
'LazyBidrectionalCollection<MapCollectionView<Dictionary<ColorScheme, UIColor>, UIColor>>' is not convertible to 'UIColor'

It seems that rather than returning an Array of values, the values method returns a more abstract collection type. Is there a way to get an Array containing the dictionary's values without extracting them in a for-in loop?



answered 4 years ago Stuart #1

As of Swift 2.0, Dictionary’s values property now returns a LazyMapCollection instead of a LazyBidirectionalCollection. The Array type knows how to initialise itself using this abstract collection type:

let colors = Array(colorsForColorSchemes.values)

Swift's type inference already knows that these values are UIColor objects, so no type casting is required, which is nice!

answered 2 years ago pjuzeliunas #2

You can also map dictionary to an array of values:

let colors = colorsForColorScheme.map { $0.1 }

Closure takes a key-value tuple from dictionary and returns just a value. So, map function produces an array of values.

answered 2 years ago GSerjo #3

you can create an extension on LazyMapCollection

public extension LazyMapCollection  {

    func toArray() -> [Element]{
        return Array(self)

colorsForColorSchemes.values.toArray() or colorsForColorSchemes.keys.toArray()

answered 9 months ago vishal kundaliya #4

Use colorsForColorScheme.map({$0.value})

comments powered by Disqus