Swift 字典:以数组形式获取值 [英] Swift Dictionary: Get values as array

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

问题描述

我有一个字典,其中包含由枚举值散列的 UIColor 对象,ColorScheme:

I have a dictionary containing UIColor objects hashed by an enum value, ColorScheme:

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

我希望能够提取此字典包含的所有颜色(值)的数组.我以为我可以使用 values 属性,就像在迭代字典值时使用的那样(for value in 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 值,values 方法返回一个更抽象的集合类型.有没有办法获取包含字典值的 Array 而无需在 for-in 循环中提取它们?

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?

推荐答案

从 Swift 2.0 开始,Dictionaryvalues 属性现在返回一个 LazyMapCollection 而不是 LazyBidirectionalCollection.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 的类型推断已经知道这些值是 UIColor 对象,所以不需要类型转换,这很好!

Swift's type inference already knows that these values are UIColor objects, so no type casting is required, which is nice!

这篇关于Swift 字典:以数组形式获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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