WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

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

   

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.