Swift Dictionary: getting values ​​as an array

I have a dictionary containing UIColor objects hashed with enum, ColorScheme :

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

I would like to be able to extract an array from all the colors (values) contained in this dictionary. I thought I could use the values property, which 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' 

Instead of returning an Array value, the values ​​method seems to return a more abstract type of collection. Is there a way to get an Array containing dictionary values ​​without highlighting them in a for-in loop?

+75
dictionary arrays swift
Nov 18 '14 at 6:41
source share
4 answers

With Swift 2.0, the Dictionary s values property now returns LazyMapCollection instead of LazyBidirectionalCollection . The Array type knows how to initialize itself using this type of abstract collection:

 let colors = Array(colorsForColorSchemes.values) 

Type Swift output already knows that these values ​​are UIColor objects, so type casting is not required, which is nice!

+173
Nov 18 '14 at 6:41
source share

You can also map the dictionary to an array of values:

 let colors = colorsForColorScheme.map { $0.1 } 

Closure takes the key-value from the dictionary and returns only the value. Thus, the map function creates an array of values.

+23
Jun 16 '16 at 12:52 on
source share

you can create an extension on LazyMapCollection

 public extension LazyMapCollection { func toArray() -> [Element]{ return Array(self) } } 

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

+4
Nov 05 '16 at 3:07
source share

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

+1
Dec 18 '17 at 9:45
source share



All Articles