Antonio
Antonio

Reputation: 21

How can I read this Dictionary in Swift?

I'm learning Swift and I have a question.

If I have a Dictionary of Strings, how I can call the value in this case?

var list: [String:[String]] = [
"A": ["a1","a2","a3"],
"B": ["b1","b2","b3"],
"C": ["c1"]
]

If I want to print all the B key, I can print so:

print(list["B"]) and this work, print me all the value in B key.

But if I want to write only the second value of B key? How can I check an example-> key: B - value: b2 ?

Upvotes: 0

Views: 85

Answers (2)

Fluidity
Fluidity

Reputation: 3995

just a safer alternative to force unwrap, and gives you a bit more control than just ?

This extracts the contents of the dictonary (the value) at key "B". Then, you just access the value (which is [String] with normal subscript:

if let bList = list["B"] {
  print( bList[1] )
} else { print("List B not found ={ ") }

Upvotes: 0

Sweeper
Sweeper

Reputation: 270780

It's quite straightforward, just do:

list["B"]![1]

If you find this confusing, here's my explanation.

As you said, list["B"] returns the whole array, i.e. ["b1", "b2", "b3"], right. To access an array, we use the subscript notation, just like you did with the dictionary. Since the position of the first item in the array is index 0, the second item is at index 1. That's why I wrote 1 in the []. However, the subscript of the dictionary returns an optional. That's why I added ! in there to unwrap it.

Upvotes: 5

Related Questions