Menu
CoddyTech

すべての支出を表示

CoddyのSwiftジャーニー「基礎」セクションの一部。レッスン 80/86。

challenge icon

チャレンジ

簡単

前のレッスンでは、「Add expense」機能を実装しました。次に、オプション "2" の「View all expenses」機能を実装しましょう。

オプション "2" を処理するようにコードを変更しましょう。

  1. ユーザーが "2" を入力したら、expenses 配列が空かどうかを確認します
  2. 配列が空の場合は、No expenses recorded. を出力します
  3. 配列に経費がある場合は、Your expenses: を出力し、その後に各経費を1行ずつ出力します。書式は - $ の後に、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プレイグラウンド