Menu
CoddyTech

For Loops and Ranges

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

R sequence indices conventionally start at one. seq_len(n) yields an empty sequence when n is zero, unlike 1:n, which then produces a descending pair. A for loop iterates values from its sequence, and c can append values although preallocation is preferable for large repeated construction.

Swift 1...3 is a closed range including 3, while 1..<3 excludes it. Array indices start at zero, independently of the range used to generate values. for-in can iterate elements directly; use indices only when an operation actually needs positions.

Both examples generate three labels. Swift's closed range includes three, while its half-open range excludes the upper bound. Translate endpoint and empty-input behavior deliberately instead of assuming a colon sequence and a Swift range have identical edge cases.

Complete R comparison program:

labels <- character()
for (row in seq_len(3L)) labels <- c(labels, paste0("R", row))
cat(paste(labels, collapse = " "), "\n", sep = "")

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 R Developers

Practice on your own: Swift playground