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

SOLVED: Day 7:Closures Part 2;Advanced Test Q.6... places[$0, default: 0] += 1 //??

Forums > 100 Days of Swift

func visitPlaces() -> (String) -> Void {

var places = [String: Int]()

return {

    places[$0, default: 0] += 1   //i dont understand 

    let timesVisited = places[$0, default: 0]  //i dont understand

    print("Number of times I've visited \($0): \(timesVisited).")

}

}

let visit = visitPlaces()

visit("London")

visit("New York")

visit("London")

Hi, the above code is from a test. I dont understand 2 lines as indicated in above quote with //.

Why is there default inside the dictionary and why is it added by 1?

Can someone help me explain this? Thank you.

1      

When you access a dictionary value using a key, it returns an Optional result, since the key you are asking for may not exist within the dictionary. You can supply a default value so that if the key doesn't exist you will get that default value back instead of a nil value.

So in the two lines you indicate, you are trying to get whatever value is stored in the dictionary under the key indicated by whatever $0 happens to be. If that key does not exist, the default value of 0 will be returned instead.

The first time you call visit("London"), that city is not in the dictionary, so you get a value of 0, to which 1 is added (because you have now visited it) and stored back in the dictionary. Same when you call visit("New York"). But the second time you call visit("London"), that key does exist, so you get back the stored value rather than the default, and 1 is added to that and stored back in the dictionary.

The second usage of places[$0, default: 0] just reads out the value from the dictionary. A default value isn't strictly necessary here since we know there will be a value, but it prevents us from having to unwrap an Optional result.

2      

thanks @roosterboy for your explanation once again!

1      

Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

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.