使用变量作为键访问 Swift 字典
Accessing Swift dictionary using variable as key
使用 SKSpriteKit 的 userData 属性,我使用以下行将网格上的 x 和 y 坐标附加到节点。
node.userData = ["x": x, "y": y]
然后我使用 touchesBegan
将数据发送到此函数。
func touched(userData: NSDictionary) {
print(userData)
}
控制台成功打印所需数据。使用这本词典...
var dictionary: [AnyHashable : Any] = [1: "Test1",
2: "Test2",
3: "Test3",
4: "Test4",
5: "Test5",
6: "Test6",
7: "Test7"
]
然后我想使用以下方法检索相关的密钥对:
dictionary[userData["x"]]
但是,我收到以下错误:
Cannot subscript a value of type 'NSDictionary' with an index of type
'String'
这是由于 Any
强制转换导致误导性诊断的典型案例。
只是为了简化问题(并摆脱 SpriteKit):
let userData: NSDictionary = ["x": 1, "y": 2]
let dictionary = [1: "Test1",
2: "Test2",
3: "Test3",
4: "Test4",
5: "Test5",
6: "Test6",
7: "Test7"
]
dictionary[userData["x"]]
诊断是:
Cannot subscript a value of type 'NSDictionary' with an index of type 'String'
但这不是真正的问题所在。主要问题是 userData["x"]
returns 一个可选的 (Any?
)。 Optional 将始终阻止它工作。但是Any?
也是一个给Swift制造各种问题的奇葩类型。 (因为 Any?
本身就是 Any
,而 Any
可以简单地提升为 Any?
。所以 Any
、Any?
、Any??
, Any???
, 等等都是有些可以互换的类型。有点乱,造成很多混乱。)
编译器寻找带有 String
和 returns 和 Int
的下标,但找不到。回滚到关于 String
是问题的诊断,这是一个非常非常迂回的方式,但不是您所期望的。
您需要确保这里有一个 Int
,并且它存在。举个例子:
if let x = userData["x"] as? Int {
dictionary[x] // "Test1"
}
使用 SKSpriteKit 的 userData 属性,我使用以下行将网格上的 x 和 y 坐标附加到节点。
node.userData = ["x": x, "y": y]
然后我使用 touchesBegan
将数据发送到此函数。
func touched(userData: NSDictionary) {
print(userData)
}
控制台成功打印所需数据。使用这本词典...
var dictionary: [AnyHashable : Any] = [1: "Test1",
2: "Test2",
3: "Test3",
4: "Test4",
5: "Test5",
6: "Test6",
7: "Test7"
]
然后我想使用以下方法检索相关的密钥对:
dictionary[userData["x"]]
但是,我收到以下错误:
Cannot subscript a value of type 'NSDictionary' with an index of type 'String'
这是由于 Any
强制转换导致误导性诊断的典型案例。
只是为了简化问题(并摆脱 SpriteKit):
let userData: NSDictionary = ["x": 1, "y": 2]
let dictionary = [1: "Test1",
2: "Test2",
3: "Test3",
4: "Test4",
5: "Test5",
6: "Test6",
7: "Test7"
]
dictionary[userData["x"]]
诊断是:
Cannot subscript a value of type 'NSDictionary' with an index of type 'String'
但这不是真正的问题所在。主要问题是 userData["x"]
returns 一个可选的 (Any?
)。 Optional 将始终阻止它工作。但是Any?
也是一个给Swift制造各种问题的奇葩类型。 (因为 Any?
本身就是 Any
,而 Any
可以简单地提升为 Any?
。所以 Any
、Any?
、Any??
, Any???
, 等等都是有些可以互换的类型。有点乱,造成很多混乱。)
编译器寻找带有 String
和 returns 和 Int
的下标,但找不到。回滚到关于 String
是问题的诊断,这是一个非常非常迂回的方式,但不是您所期望的。
您需要确保这里有一个 Int
,并且它存在。举个例子:
if let x = userData["x"] as? Int {
dictionary[x] // "Test1"
}