GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Dictionary default values test question # 4

Forums > 100 Days of SwiftUI

let capitals = ["England": "London", "Wales": "Cardiff"] let scotlandCapital = capitals["Scotland"]

How is this valid? I'm honestly confused. They are creating a new constant named scotlandCaptial and assigning it the value of "Scotland in the constant "capitals" EXCEPT, Scotland isn't lsted there, wouldn't it return an error?

   

Dictionaries return optional values. If we try to read an element with a key that does not exist, the value returned is nil

let scotlandCapital = capitals["Scotland"] // This will return nil

   

@Yuri gives the right answer!

EXCEPT, Scotland isn't lsted there, wouldn't it return an error?

In older languages, yes! Your application wouldn't compile, or perhaps would crash on a line like this. But as Yuri noted, Swift will attempt to find the key value in the dictionary for you. But if it doesn't find the key value, it will return nil allowing you to gracefully continue with logic appropriate to your application.

This is one of the strengths of the Optional type and why it's imporant to twist your mind around the concept!

Keep Coding!

Also: please take a moment to review the markup tag for adding code to your forum questions.

See -> Adding Code snips to Forum Messages

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.