斯威夫特词典:获取值数组 [英] Swift Dictionary: Get values as array

查看:92
本文介绍了斯威夫特词典:获取值数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含由枚举值散列的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆