In Swift can I use a tuple as the key in a dictionary?(在 Swift 中,我可以使用元组作为字典中的键吗?)
问题描述
我想知道是否可以以某种方式使用 x, y 对作为我的字典的键
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>()
但我得到了错误:
Cannot convert the expression's type '<<error type>>' to type '$T1'
和错误:
Type '(x: Int, y: Int)?' does not conform to protocol 'Hashable'
那么..我们怎样才能使它符合?
So.. how can we make it conform?
推荐答案
Dictionary
的定义是struct Dictionary<KeyType : Hashable, ValueType>: ...
,即key的类型必须符合Hashable
协议.但是语言指南告诉我们 协议可以被类、结构体和枚举采用,即不能被元组采用.因此,元组不能用作 Dictionary
键.
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.
一种解决方法是定义一个包含两个 Int 的可散列结构类型(或您想要放入元组中的任何内容).
A workaround would be defining a hashable struct type containing two Ints (or whatever you want to put in your tuple).
这篇关于在 Swift 中,我可以使用元组作为字典中的键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Swift 中,我可以使用元组作为字典中的键吗?
基础教程推荐
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01