Menu
CoddyTech

For Loops and Ranges

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

Luau numeric for includes its limit when reached, so 0 through 2 produces three labels. table.insert appends them to a dense one-based sequence; the values being generated need not match their storage indices. General tables with holes do not support the same simple length assumptions.

Swift 0..<3 excludes its upper bound and therefore visits the same three numeric values. A closed range uses ..., including its endpoint. Swift arrays use zero-based indices, but for-in can iterate elements directly. Choose range bounds by the required values rather than by the source collection's index convention.

Luau

Complete Luau console program:

main.luau

local rows: {string} = {}
for index = 0, 2 do table.insert(rows, `R{index}`) end
print(table.concat(rows, ","))

Swift

Complete program; compile the listed files together:

main.swift

import Foundation
var rows: [String] = []
for index in 0..<3 { rows.append("R\(index)") }
print(rows.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 Luau Developers

Practice on your own: Swift playground