Swift Dictionary: Get values as array

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:

  • What's the difference between & Array<Int>?
  • How can I detect which annotation was selected in MapView
  • How to check a single time if UserDefaults is empty
  • Swift sort array of objects based on boolean value
  • Swift Arrays of Multiple Types
  • Add constraints to generic parameters in extension
  • 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?

    4 Solutions Collect From Internet About “Swift Dictionary: Get values as array”

    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!

    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.

    you can create an extension on LazyMapCollection

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

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

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