For Loops and Ranges
Lesson 13 of 48 in Coddy's Swift for C++ Developers course.
C++ supports counter-based and range-based for loops, while Swift for-in consumes a sequence of values. Swift ..< excludes an upper bound and ... includes it; neither reversed closed-range bounds nor changing a loop binding is a countdown mechanism. The target stride explicitly uses a negative step and an exclusive endpoint. C++ expresses the same traversal through its update and condition. For a nonnegative count that may be zero, 0..<count can be empty. Continue skips an iteration and break exits, but the collection or range must still have the intended endpoint and direction contract.
C++
Complete program file: main.cpp.
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
int main() {
bool first = true;
for (int n = 6; n > 0; n -= 2) {
if (!first) std::cout << ',';
first = false;
std::cout << n;
}
std::cout << '\n';
}
Swift
Complete program file: main.swift.
var labels: [Int] = []
for n in stride(from: 6, to: 0, by: -2) { labels.append(n) }
print(labels.map(String.init).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 C++ 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