Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Dictionary: Get values as array

People also ask

How do I map an array in Swift?

Example 2: Uppercase Array Of Strings Using map() In the above example, we have used the map() and uppercased() methods to transform each element of the languages array. The uppercased() method converts each string element of an array to uppercase. And the converted array is stored in the result variable.

Is Swift dictionary ordered?

There is no order. Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined. If you need an ordered collection of values, I recommend using an 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})


you can create an extension on LazyMapCollection

public extension LazyMapCollection  {

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

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


Firstly, from the following statement, it seems that your variable(dictionary) name is colorsForColorScheme

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

while you are trying to get the values from colorsForColorSchemes dictionary when you did-

let colors: [UIColor] = colorsForColorSchemes.values

which should give you a compile time error. Anyways I am assuming that you had a typo, and you dictionary's name is colorsForColorSchemes. So, here is the solution-

As mentioned earlier, because of the type inference property in swift, your code can infer that the returned type from the .values function is returning an array of UIColor. However, Swift wants to be type-safe, so when you store the values in the colors array, you need to explicitly define that. For swift 5 and above, now you could just do following-

let colors = [UIColor](colorsForColorSchemes.values)

You can also use flatMap:

let colors = colorsForColorScheme.values.flatMap { $0 }