Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Collections and Control Flow Control Flow With Conditional Statements Working With Switch Statements

Harshil Sharma
Harshil Sharma
1,896 Points

programme not working until i change the arrays type to optional type please explain

THis code works if i change the arrays type to optional string .please explain why its not working

operators.swift
var europeanCapitals: [String?] = []
var asianCapitals: [String?] = []
var otherCapitals: [String?] = []

let world = [
  "BEL": "Brussels", 
  "LIE": "Vaduz", 
  "BGR": "Sofia", 
  "USA": "Washington D.C.", 
  "MEX": "Mexico City", 
  "BRA": "Brasilia", 
  "IND": "New Delhi", 
  "VNM": "Hanoi"]

for (key, value) in world {

    // enter your code below
    switch key {
    case "BEL", "LIE", "BGR" : europeanCapitals.append(world[key])
    case "IND", "VNM" : asianCapitals.append(world[key])
    default : otherCapitals.append(world[key])
    }
    // End code
}

2 Answers

Hi there,

In your for loop you are pulling out the key and the value from world. You are then switching on key. If that key matches your case you are then accessing world using key. What does that get you? The value. But you already have the value from the beginning of your loop.

If you just use .append(value) it'll work without needing to use optionals. I think that's a requirement as it is possible that world[key] might produce nothing so the array needs to be prepared for that occurrence. I'm not wholly sure, though!

Steve.

Yes, that is the reason. You can also use the bang:

europeanCapitals.append(world[key]!)

The error states this around the world[key] code:

error: value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?

So, the ! or ? is required to protect against world[key] coming back with nothing, I think.

But just using the already-unwrapped value is the best way forward.

Harshil Sharma
Harshil Sharma
1,896 Points

thanks, steve got it. I used ! after world[key] and it worked. But your first suggestion was more likely approach to be followed in future.

Glad you understand it now. :+1: :smile: