0
0
Swiftprogramming~15 mins

Dictionary methods and default values in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Dictionary methods and default values
📖 Scenario: You are managing a small fruit store. You want to keep track of how many fruits you have in stock.
🎯 Goal: Build a Swift program that uses a dictionary to store fruit counts, safely access values with default counts, and update the stock.
📋 What You'll Learn
Create a dictionary called fruitStock with exact fruit counts
Create a variable called defaultCount with the value 0
Use the dictionary's default value feature to get counts safely
Update the stock count for a fruit using dictionary methods
Print the final stock counts
💡 Why This Matters
🌍 Real World
Managing inventory counts in a store or warehouse where some items may not be in stock yet.
💼 Career
Understanding dictionary methods and default values is essential for safe data handling in app development and backend programming.
Progress0 / 4 steps
1
Create the initial fruit stock dictionary
Create a dictionary called fruitStock with these exact entries: "Apple": 10, "Banana": 5, "Orange": 8
Swift
Need a hint?

Use Swift dictionary syntax with square brackets and colons.

2
Add a default count variable
Create a variable called defaultCount and set it to 0
Swift
Need a hint?

Use let or var to create the variable.

3
Use dictionary default value to get counts safely
Create a variable called mangoCount and set it to the count of "Mango" in fruitStock using the dictionary's default value feature with defaultCount
Swift
Need a hint?

Use the dictionary subscript with default: to avoid nil.

4
Update stock and print results
Increase the count of "Banana" in fruitStock by 3 using the dictionary's default value feature and then print the updated fruitStock dictionary
Swift
Need a hint?

Use the dictionary subscript with default: to add 3 to "Banana" count, then print the dictionary.