-8

the codes simple:

var dictionnary: [Int: Int] = [25: 32]
var test = "dictionary"

print (dictionary[25])
print (test[25])

I want to access to the content the dictionary like in the last line of code. I have to detect the name of the dictionary i have to use. So I am obliged to store the name of the dictionary in a variable of type String. a get this error :

error i get with last line of code

how can I proceed?

Ok, I tried to make a simple example to explain my problem and I made a mistake. My problem is not related to converting string to a variable name or something else.

In fact I have 10 dictionaries with data in each. I need to identify the good one in order to grab my data.

I obtained a variable of type string containing the name of the good dictionary but when I try to use it to access to the content of this dictionary I obtain the error mentioned.

I will try to explain this correctly when I will be able to post again...

D4vi9
  • 13
  • 4

2 Answers2

0

You've already named your dictionary with this code:

var dictionary: [Int: Int] = [25: 32]

Your dictionary is called "dictionary" (you spelled it incorrectly but I think this is what you were going for.

To access the value for the key 25, you've done that correctly:

print (dictionary[25])

There's no need to make a variable called test. A string doesn't act like an array in swift, but if it did

print(test[25])

would be accessing the 26th character in the string "dictionary", which is non-existant.

-1

I think you want

var test = dictionary

Remove the quotations

Pranav Wadhwa
  • 7,666
  • 6
  • 39
  • 61
  • This solve my problem. – D4vi9 Jun 12 '16 at 20:59
  • 1
    You should note that this is creating a copy, not a reference of `dictionary` due to the nature of value types in Swift (`Dictionary` is a `struct`). Any mutations to your `dictionary` variable will not be reflected on `test`. – Hamish Jun 12 '16 at 21:12
  • @D.PEPIN if my answer helped you, could you please accept it? Thanks! – Pranav Wadhwa Jun 12 '16 at 22:13