Sasha doesn't quite grok the reasons for defaults when browsing a dictionary.
but I can't understand some statements
Here's another example for you.
Open your Contacts app on your iPhone. Contacts is full of phone number, email addresses, and home addresses for your friends, business partners, classmates, and family.
Now, in the search bar at the top of the screen, type my name: Obelix
Probably, you got a message in the app telling you: No Results
You just simulated a dictionary lookup. You gave the application a KEY, and expected a VALUE in return. However the key you provided did NOT have an associated value!
So you are the developer. You are in charge of your own logic.
Key - Value Pairs
When you provide a key to your dictionary, and it cannot find the key in your dictionary, what value should the dictionary return?
On the one hand, a failed lookup normally returns nil
.
// Look up obelix in your phoneNumberDictionary.
// If obelix is NOT FOUND, the dictionary returns nil.
let obelixPhoneNumber = phoneNumberDictionary["obelix"] // <- Return nil. No entry for obelix.
On the otherhand, you may have other rules in your application. For example, you KNOW that obelix plays the Balalaika in your local orchestra. But when you look him up in your phoneNumberDictionary, you don't want to process nil
values. Obelix exists, he just doesn't have a phone number in your dictionary.
Instead, you may want to return a phone number like this: +7 000-0000-000
So instead of returning nil
, you provide a default value. Your code will look like:
// If obelix does NOT have a number in the phoneNumberDictionary,
// then provide a reasonable default
let obelixPhoneNumber = phoneNumberDictionary["obelix", default: "+7 000-0000-000"]
You are the programmer. It's your choice how you want to deliver data to your application.