Menu
CoddyTech

For Loops and Ranges

Lesson 13 of 48 in Coddy's Swift for Python Developers course.

Python range excludes its stop value. Swift ..< also creates a half-open range, while ... includes both ends. These ranges require valid ordered bounds, so handle an empty or reversed interval before constructing a closed range.

Swift for ... in visits sequence elements, and an unused loop binding can be written as _. For a count-controlled loop starting at zero, 0..<count is empty when count is zero. Use stride for explicit steps when the algorithm needs them.

This program creates row labels in order. It demonstrates an accumulator and an inclusive endpoint. The task counts values meeting a divisibility rule instead of producing row labels.

Complete Python comparison program:

labels = []
for row in range(1, 4):
    labels.append(f"R{row}")
print(" ".join(labels))

Complete Swift comparison program, compiled from these files:

main.swift

var labels: [String] = []
for row in 1...3 {
    labels.append("R\(row)")
}
print(labels.joined(separator: " "))
challenge icon

Challenge

Easy

Implement multiples(upTo:of:): count multiples of the divisor in the inclusive range 0 through limit, including zero. Input is limit 0 through 1000 and divisor 1 through 100. Output the count.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
return multiples(upTo: 14, of: 4) == 4 && multiples(upTo: 0, of: 2) == 1 && multiples(upTo: 8, of: 4) == 3
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Python Developers

Practice on your own: Swift playground