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 中,我可以使用元组作为字典中的键吗?


基础教程推荐
- 固定小数的Android Money Input 2022-01-01
- 在 iOS 上默认是 char 签名还是 unsigned? 2022-01-01
- Android ViewPager:在 ViewPager 中更新屏幕外但缓存的片段 2022-01-01
- :hover 状态不会在 iOS 上结束 2022-01-01
- 如何使 UINavigationBar 背景透明? 2022-01-01
- LocationClient 与 LocationManager 2022-01-01
- 使用 Ryzen 处理器同时运行 WSL2 和 Android Studio 2022-01-01
- Android文本颜色不会改变颜色 2022-01-01
- “让"到底是怎么回事?关键字在 Swift 中的作用? 2022-01-01
- 如何使用 YouTube API V3? 2022-01-01