Guard and Early Exit
Lesson 8 of 48 in Coddy's Swift for C++ Developers course.
C++ commonly uses an early return after an invalid or absent-input check. Swift guard expresses the precondition of the remaining scope and requires its else branch to leave that scope. A guard-let binding remains available after success, unlike an if-let binding confined to its success branch. The source uses std::optional<std::string> and uppercase logic for ASCII lowercase characters, while the target uppercased operation supports broader Unicode behavior. The displayed ASCII word has matching results. A guard is not an exception handler and need not unwrap an optional; it can guard any Boolean invariant.
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>
std::string render(std::optional<std::string> input) {
if (!input) return "untitled";
std::string text = *input;
for (char &c : text) if (c >= 'a' && c <= 'z') c = static_cast<char>(c - 'a' + 'A');
return text;
}
int main() {
std::cout << render(std::nullopt) << '\n';
std::cout << render(std::string("go")) << '\n';
}
Swift
Complete program file: Functions.swift.
func render(_ input: String?) -> String {
guard let caption = input else { return "untitled" }
return caption.uppercased()
}Complete program file: main.swift.
print(render(nil))
print(render("go"))Challenge
EasyImplement remainder(balance:withdrawal:): reject a nonpositive withdrawal or one exceeding the balance; otherwise return the balance left. Input has balance 0 through 10000 and withdrawal -100 through 10000. Output the remainder or rejected.
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 remainder(balance: 19, withdrawal: 4) == 15 && remainder(balance: 19, withdrawal: 0) == nil && remainder(balance: 19, withdrawal: 20) == nil
}
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 RulesPractice on your own: Swift playground