Clear All
Part of the Fundamentals section of Coddy's Swift journey — lesson 82 of 86.
Challenge
EasyIn the previous lesson, you implemented the "Show total and average" feature. Now, implement the "Clear all expenses" feature for option "4".
Modify your code to handle option "4":
- When the user enters
"4", remove all elements from theexpensesarray - Print
All expenses cleared!after clearing the array - All other options (
"1","2","3", and"5") should continue working as before
Hint: Use the removeAll() method to clear all elements from the array.
Expected behavior:
- When
"4"is entered, clear the expenses array and confirm with a message - After clearing, viewing expenses should show
No expenses recorded. - After clearing, showing total/average should show
No expenses to calculate.
Example interaction:
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
15.0
Expense added!
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
25.0
Expense added!
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
2
Your expenses:
- $15.0
- $25.0
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
4
All expenses cleared!
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
2
No expenses recorded.
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
5
Goodbye!Try it yourself
// Daily Expense Tracker - Menu Display
var expenses: [Double] = []
while true {
// TODO: Write your code below to print the menu options
// Each option should be on its own line with the format: "number. option text"
print("1. Add expense")
print("2. View all expenses")
print("3. Show total and average")
print("4. Clear all expenses")
print("5. Exit")
let choice = readLine()
if choice == "1" {
print("Enter expense amount:")
if let input = readLine(), let amount = Double(input) {
expenses.append(amount)
print("Expense added!")
}
} else if choice == "2" {
if expenses.isEmpty {
print("No expenses recorded.")
} else {
print("Your expenses:")
for expense in expenses {
print("- $\(expense)")
}
}
} else if choice == "3" {
if expenses.isEmpty {
print("No expenses to calculate.")
} else {
let total = expenses.reduce(0, +)
let average = total / Double(expenses.count)
print("Total: $\(total)")
print("Average: $\(average)")
}
} else if choice == "4" {
print("Coming soon...")
} else if choice == "5" {
print("Goodbye!")
break
} else {
print("Coming soon...")
}
}All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input12Arrays Basics
Declaring An ArrayAccessing ElementsModifying ArraysArray MethodsRecap - Product ListRecap - Reversed ArrayTuples15Daily Expense Tracker
Project OverviewExit The Program