Skip to Content

Vòng lặp while và repeat-while trong Swift

1. While loop

var count = 1 while count <= 5 { print(count) count += 1 } // Output: 1, 2, 3, 4, 5

2. Repeat-while loop

Tương tự do-while trong các ngôn ngữ khác:

var count = 1 repeat { print(count) count += 1 } while count <= 5 // Khác biệt: chạy ít nhất 1 lần var x = 10 repeat { print(x) // In ra 10 } while x < 5 // false nhưng vẫn chạy 1 lần

3. Infinite loop

var count = 0 while true { print(count) count += 1 if count >= 5 { break } }

4. Ví dụ thực tế: Menu

var choice: Int repeat { print(""" === MENU === 1. Start 2. Settings 3. Exit Choose: """) choice = Int(readLine() ?? "0") ?? 0 switch choice { case 1: print("Starting...") case 2: print("Settings...") case 3: print("Goodbye!") default: print("Invalid choice") } } while choice != 3

📝 Tóm tắt

  • while - Kiểm tra trước khi chạy
  • repeat-while - Chạy ít nhất 1 lần
  • while true - Infinite loop
  • Dùng break để thoát
Last updated on