While and Repeat Loops
Lesson 14 of 48 in Coddy's Swift for R Developers course.
R while checks before the body. R repeat instead runs until code explicitly breaks; it has no built-in trailing while condition. A repeat loop can implement a post-test pattern by placing its test and break at the end. Conditions must resolve to a scalar nonmissing decision.
Swift while checks before its body and repeat-while checks afterwards. The latter always runs at least once and continues only while its Bool condition holds. A direct keyword substitution for R repeat is insufficient because the R exit test may be anywhere inside its body.
The positive folding example makes R floor division and Swift truncation agree. Both stop at four after three updates. Choose a progress measure and verify the initially-complete input, especially when converting an unbounded repeat loop to a conditional target loop.
Complete R comparison program:
span <- 32L
folds <- 0L
while (span > 5L) {
span <- span %/% 2L
folds <- folds + 1L
}
cat(span, folds, sep = " ")
cat("\n")
Complete Swift comparison program, compiled from these files:
main.swift
var length = 32
var folds = 0
while length > 5 {
length /= 2
folds += 1
}
print(length, folds)Challenge
EasyImplement digitSum(_:) for a nonnegative integer 0 through 1000000. Return the sum of its decimal digits. Input and output are each one integer.
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 digitSum(406) == 10 && digitSum(99) == 18 && digitSum(0) == 0
}
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 R 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