Menu
CoddyTech

Просмотр всех расходов

Часть раздела Основы путешествия по Swift на Coddy. Урок 80 из 86.

challenge icon

Задание

Легко

На предыдущем уроке ты реализовал функцию «Add expense». Теперь реализуй функцию «View all expenses» для варианта "2".

Измени код, чтобы обрабатывать вариант "2":

  1. Когда пользователь вводит "2", проверь, пуст ли массив expenses
  2. Если массив пуст, выведи No expenses recorded.
  3. Если в массиве есть расходы, выведи Your expenses:, а затем каждый расход с новой строки в формате - $, после которого указывается сумма так, как Swift выводит значение типа Double (например, 25.50 выводится как - $25.5)
  4. Для вариантов "3" и "4" по-прежнему должно выводиться Coming soon...
  5. Варианты "1" и "5" должны продолжать работать как раньше

Ожидаемое поведение:

  • Если введено "2" и расходов нет, выведи No expenses recorded.
  • Если введено "2" и расходы есть, выведи заголовок и перечисли каждый расход, поставив перед ним дефис и знак доллара

Пример взаимодействия:

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
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
2
Your expenses:
- $25.5
- $10.0
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
5
Goodbye!

Попробуйте сами

// 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" {
        print("Coming soon...")
    } else if choice == "3" {
        print("Coming soon...")
    } else if choice == "4" {
        print("Coming soon...")
    } else if choice == "5" {
        print("Goodbye!")
        break
    } else {
        print("Coming soon...")
    }
}

Все уроки раздела Основы

Потренируйтесь самостоятельно: Песочница Swift