Accessing Swift dictionary using variable as key -


using skspritekit's userdata property, have used following line attach x , y co-ordinates on grid, node.

node.userdata = ["x": x, "y": y] 

i using touchesbegan send data function.

func touched(userdata: nsdictionary) {         print(userdata)    } 

the console prints data required. using dictionary...

var dictionary: [anyhashable : any] = [1: "test1",                           2: "test2",                           3: "test3",                           4: "test4",                           5: "test5",                           6: "test6",                           7: "test7" ] 

i want retrieve relevant key-pair using:

dictionary[userdata["x"]] 

however, following error:

cannot subscript value of type 'nsdictionary' index of type 'string'

this classic case of misleading diagnostic due any casting.

just simplify problem (and rid of 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"]] 

the diagnostic is:

cannot subscript value of type 'nsdictionary' index of type 'string' 

but that's not problem. main problem userdata["x"] returns optional (any?). optional keep working. any? bizarro-type creates kinds of problems swift. (because any? any, , any can trivially promoted any?. any, any?, any??, any???, etc. interchangable types. it's bit of mess , creates lot of confusion.)

the compiler goes looking subscript takes string , returns int, , can't find it. rolls diagnostic string being problem, very, roundabout way true, isn't expecting.

you need makes sure have int here, , exists. 1 example:

if let x = userdata["x"] as? int {     dictionary[x] // "test1" } 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -