Stuart Stuart - 1 year ago 76
Swift Question

Swift Dictionary: Get values as array

I have a dictionary containing

objects hashed by an enum value,

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
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
of values, the
method returns a more abstract collection type. Is there a way to get an
containing the dictionary's values without extracting them in a

Answer Source

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!