プログラムを終了する
CoddyのSwiftジャーニー「基礎」セクションの一部。レッスン 78/86。
チャレンジ
簡単前のレッスンでは、支出トラッカーのメニューを表示しました。次は、ユーザーが終了を選ぶまでメニューを繰り返し表示し、ユーザーの入力を読み取るループを追加しましょう。
コードを次のように変更しましょう。
- 支出を保存するために、型が
[Double]の空の配列expensesを作成する while trueループを使って、プログラムを実行し続ける- ループ内で、メニューを(前と同じように)表示する
readLine()を使ってユーザーの選択を読み取る- ユーザーが
"5"を入力したら、Goodbye!を表示し、breakを使ってループを終了する - それ以外の入力の場合は、
Coming soon...を表示する(ほかの選択肢は後のレッスンで実装します)
期待される動作:
- ユーザーが
"5"を入力するまで、メニューが繰り返し表示される "5"が入力されたら、Goodbye!を表示してループを終了する"1"、"2"、"3"、"4"のいずれか(またはその他の入力)が選択されたら、Coming soon...を表示して、再びメニューを表示する
実行例:
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Coming soon...
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
// 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")基礎のすべてのレッスン
自分で練習してみよう: Swiftプレイグラウンド