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

查看:42
本文介绍了在 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 中,我可以使用元组作为字典中的键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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