Swift While, Repeat and Loop Control
Repeat bounded work and make every stopping path visible.
How it works
while checks before its body and repeat-while checks afterward. continue advances to the next iteration; break exits the current loop unless a label identifies another one. A manual counter must change on every path that is meant to make progress.
Run this Swift example
Install the toolchain for your platform from Swift.org, then check swift --version. The reviewed portable baseline is Swift 6.4.2 in Swift 6 mode on Ubuntu 26.04 x86_64 through the PC’s existing WSL installation. These are real Linux executions, not claims of Windows-native or Apple-platform test results. Windows Swift has separate C++/SDK prerequisites in its official setup guide.
Save the complete source as while-repeat-control.swift in a new learning folder. On Linux/macOS compile with swiftc -swift-version 6 -parse-as-library while-repeat-control.swift -o lesson, then run ./lesson. On a configured Windows toolchain use an output such as lesson.exe and run .\lesson.exe. The parse-as-library option supports the explicit @main entry point used by these sources. Compile each ordinary lesson separately.
Bhylu has no Swift browser runner. The JavaScript/Python editors do not run these sources; Apache, PHP and MySQL are not required. Downloads are source text, never executable teaching endpoints.
Download the complete while-repeat-control.swift · Download all source files with hash checks
For the optional collection, save download-examples.mjs in a new folder and run node download-examples.mjs. A local preview uses node download-examples.mjs http://127.0.0.1:8000/examples/swift/. It refuses an existing bhylu-swift-examples folder and installs or executes no Swift automatically. Apple-only files remain separate Xcode learning examples, not a portable Swift package target.
Example
@main
struct Lesson {
static func main() {
var remaining = 3
while remaining > 0 {
print(remaining)
remaining -= 1
}
var attempts = 0
repeat { attempts += 1 } while attempts < 1
for number in 0...4 {
if number == 0 { continue }
if number == 3 { break }
print("item", number)
}
print("attempts", attempts)
}
}
Expected result
3 2 1 item 1 item 2 attempts 1
The repeat loop demonstrates the guaranteed first pass. The final loop skips zero and stops before three. A nested loop can use a label, but extracting a function often makes the exit easier to understand.
Primary references: The Swift Programming Language and Apple framework documentation. Use the selected platform’s current requirements. Fictional workshop examples do not establish production safety or deployment approval.