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 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.
More readable version of the same code:
let colors = colorsForColorScheme.map { (scheme, color) in
return color
}
UPDATE
From Xcode 9.0, dictionary values can be accessed using values
property, which conforms to Collection
protocol:
let colors = colorsForColorScheme.values
Typically you just want it as an array:
let colors = Array(dict.values)
and that's it.
Use colorsForColorScheme.map({$0.value})