在Swift中,我可以使用元组作为字典中的关键字吗? [英] In Swift can I use a tuple as the key in a dictionary?
问题描述
let activeSquares =字典<(x:Int,y:Int),SKShapeNode>()
但是我得到错误:
无法将表达式的类型'<< error type>'转换为'$ T1'$ b' $ b
和错误:
code>类型'(x:Int,y:Int)?'不符合协议'Hashable'
所以..我们如何使它符合?
字典的定义
是 struct Dictionary< KeyType:Hashable,ValueType> :...
,即密钥的类型必须符合协议 Hashable
。但语言指南告诉我们,协议可以由类,结构体和枚举采用,即不由元组。因此,元组不能用作字典
键。
解决方法是定义包含两个Ints的可分析结构类型(或者你想要放入你的元组的任何东西)。
I'm wondering if I can somehow use an x, y pair as the key to my dictionary
let activeSquares = Dictionary <(x: Int, y: Int), SKShapeNode>()
But I get the error:
Cannot convert the expression's type '<<error type>>' to type '$T1'
and the error:
Type '(x: Int, y: Int)?' does not conform to protocol 'Hashable'
So.. how can we make it conform?
The definition for Dictionary
is struct Dictionary<KeyType : Hashable, ValueType> : ...
, i.e. the type of the key must conform to the protocol Hashable
. But the language guide tells us that protocols can be adopted by classes, structs and enums, i.e. not by tuples. Therefore, tuples cannot be used as Dictionary
keys.
A workaround would be defining a hashable struct type containing two Ints (or whatever you want to put in your tuple).
这篇关于在Swift中,我可以使用元组作为字典中的关键字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!