斯威夫特词典:获取值数组 [英] Swift Dictionary: Get values as array
问题描述
我有一个包含由枚举值散列的UIColor
对象字典,到ColorScheme
:
I have a dictionary containing UIColor
objects hashed by an enum value, ColorScheme
:
var colorsForColorScheme: [ColorScheme : UIColor] = ...
我希望能够提取由本词典包含的所有颜色(值)的数组。我想在dictionary.values迭代字典中的值(的价值时,我可以使用
),但这返回一个错误:值
属性,使用{...}
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:
let colors: [UIColor] = colorsForColorSchemes.values
~~~~~~~~~~~~~~~~~~~~~^~~~~~~
'LazyBidrectionalCollection<MapCollectionView<Dictionary<ColorScheme, UIColor>, UIColor>>' is not convertible to 'UIColor'
看来,而不是返回值的阵列
的值
方法返回一个更抽象的集合类型。有没有办法得到一个 Array包含字典中的值,而不在
?换的
循环提取它们
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?
推荐答案
由于雨燕2.0,词典
的值
属性现在返回 LazyMapCollection
,而不是 LazyBidirectionalCollection
。在阵列
类型都知道如何使用这个抽象的集合类型来初始化本身:
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)
斯威夫特的类型推断已经知道这些值的UIColor
的对象,所以不需要类型转换,这是很好的!
Swift's type inference already knows that these values are UIColor
objects, so no type casting is required, which is nice!
这篇关于斯威夫特词典:获取值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!