Menu
CoddyTech

While and Repeat Loops

Lesson 14 of 48 in Coddy's Swift for Python Developers course.

A Python while loop checks truthiness before each pass. Swift while checks a Boolean condition before each pass. Swift also has repeat ... while, which checks after the body and therefore runs at least once.

Both forms need a path toward termination unless an explicit break exits. Update the state used by the condition on each relevant pass. A continue skips remaining statements in the body, so place essential progress updates where they cannot be bypassed.

The example repeatedly halves a sheet length until it fits a limit. It illustrates loop state, not decimal digit extraction. For the task, inspect how its integer state changes toward a stopping condition.

Complete Python comparison program:

length = 32
folds = 0
while length > 5:
    length //= 2
    folds += 1
print(length, folds)

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 icon

Challenge

Easy

Implement 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") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Python Developers

Practice on your own: Swift playground