3

I have the following swift dictionary

var List = [

   2543 : [ "book", "pen" ],
   2876 : [ "school", "house"]
]

How can i access the array values ?

println(List[2543][0]) 

The above code gives error "could not find member subscript"

and it should print "book"

3 Answers 3

7

Note that subscript returns an optional. We have to force unwrapping:

println(list[2543]![0])

Or use optional chaining

println(list[2543]?[0])
Sign up to request clarification or add additional context in comments.

Comments

3
println(list[2543]![0])

Remember, dictionary subscript returns an Optional, not an array or whatever is inside the dictionary value.

1 Comment

The important thing to understand is that Optional is itself a type (an enum). It contains a value (or nil) inside itself, but you cannot talk directly to it as if it were the value.
0

Just try with following code:

var dic = List[0];
println("values \(dic)") 

OR

println(list[2543]![0])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.