Menu
Coddy logo textTech

Add Expense

Part of the Fundamentals section of Coddy's Swift journey — lesson 79 of 86.

challenge icon

Challenge

Easy

In the previous lesson, you created a menu loop that exits when the user enters "5". Now, implement the "Add expense" feature for option "1".

Modify your code to handle option "1":

  1. When the user enters "1", print Enter expense amount:
  2. Read the expense amount using readLine()
  3. Convert the input to a Double and append it to the expenses array
  4. Print Expense added! after successfully adding the expense
  5. Options "2", "3", and "4" should still print Coming soon...
  6. Option "5" should still print Goodbye! and exit

Expected behavior:

  • When "1" is entered, prompt for the expense amount, add it to the array, and confirm
  • The menu continues to display after each action until "5" is entered

Example interaction:

1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
25.50
Expense added!
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
10.00
Expense added!
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 == "5" {
        print("Goodbye!")
        break
    } else {
        print("Coming soon...")
    }
}

All lessons in Fundamentals