UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

3      

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.

4      

thanks @roosterboy for your explanation once again!

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.