For Loops and Ranges
Lesson 13 of 48 in Coddy's Swift for Lua Developers course.
Lua numeric for includes its limit when the step reaches that limit. This loop visits 1, 2 and 3. Dense Lua sequences conventionally begin at index 1, and appending at #labels + 1 maintains that dense layout. Holes make length and sequence iteration unsuitable as a general table-entry count.
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 programs build three labels and join them with spaces. When translating a numeric loop, preserve its endpoint policy and step instead of just shifting the first value. An empty or descending traversal needs its own deliberate representation in Swift.
Complete Lua comparison program:
local labels = {}
for row = 1, 3 do
labels[#labels + 1] = "R" .. row
end
print(table.concat(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
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Lua Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry Rules3Control Flow
Switch and PatternsEnums as Finite ChoicesFor Loops and RangesWhile and Repeat LoopsRecap: Sequence ScanPractice on your own: Swift playground