在Swift中,我可以使用元组作为字典中的关键字吗? [英] In Swift can I use a tuple as the key in a dictionary?

查看:100
本文介绍了在Swift中,我可以使用元组作为字典中的关键字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我是否可以使用x,y对作为我的字典的关键字

  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屋!

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