bhylu.com

Advertisements

Swift Ranges and For Loops

Visit values with clear endpoint and ordering rules.

How it works

A closed range includes both ends, while a half-open range excludes its upper end. for-in works with sequences, and enumerated supplies an offset and element. An enumeration offset is not a general collection index, especially for a slice with retained indices.

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 ranges-for-loops.swift in a new learning folder. On Linux/macOS compile with swiftc -swift-version 6 -parse-as-library ranges-for-loops.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 ranges-for-loops.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

ranges-for-loops.swift


@main
struct Lesson {
    static func main() {
        for number in 1...3 { print(number) }
        let rooms = ["Cedar", "Ash"]
        for (offset, room) in rooms.enumerated() {
            print(offset + 1, room)
        }
    }
}

Expected result

1
2
3
1 Cedar
2 Ash

The first loop includes three. The second prints a human-facing position in the original array order. A numeric range requires sensible bounds; use indices when iterating actual array positions. Array.forEach is a closure-based method; return from that closure does not provide loop break or continue. Prefer for-in when you need those controls.

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.

Advertisements