While and Repeat Loops
Lesson 14 of 48 in Coddy's Swift for JavaScript Developers course.
JavaScript while and Swift while test before entering the body. JavaScript do-while corresponds to Swift repeat-while, which executes once before checking continuation. This first-attempt difference matters even when the condition is initially false.
Both programs grow capacity to eight and count one post-test visit. Swift needs var for changed values and += 1 instead of increment syntax. Its condition must be Bool rather than an arbitrary truthy value. Check termination and the initial state separately when choosing the loop form.
JavaScript
Complete JavaScript console program:
main.js
let capacity = 1;
while (capacity < 6) capacity *= 2;
let visits = 0;
do { visits++; } while (false);
console.log(capacity, visits);
Swift
Complete program; compile the listed files together:
main.swift
import Foundation
var capacity = 1
while capacity < 6 { capacity *= 2 }
var visits = 0
repeat { visits += 1 } while false
print(capacity, visits)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 JavaScript 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