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:

  • Sorting an array of doubles or CLLocationDistance values on the iPhone
  • UIImage Loop Through Pixel Highly Inefficient?
  • Non-optional expression of type 'AnyObject' used in a check for optionals
  • Swift - Check if array contains element with property
  • Checking if a metatype is an Array with an Element type of kind MyProtocol
  • Pushing Sound files to an Array with Swift
  • 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})