Menu
CoddyTech

While and Repeat Loops

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

GDScript while tests its condition before each pass and can run zero times. Swift while does the same with a Bool condition, and Swift additionally provides repeat-while for a body that must run before the first continuation test. GDScript does not have the same post-test loop syntax.

The program halves a bounded positive integer until it becomes at most five. Both executions reach four after three updates. Swift var permits compound updates, and its += syntax is distinct from increment operators that Swift does not provide.

Check termination and the initial empty case independently. Replacing while with repeat-while changes behavior when the original condition is already false.

Complete GDScript comparison program:

extends SceneTree

func _init():
    var length = 32
    var folds = 0
    while length > 5:
        length = length / 2
        folds += 1
    print(length, " ", folds)
    quit()

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 GDScript Developers

Practice on your own: Swift playground