Guard and Early Exit
Lesson 8 of 48 in Coddy's Swift for C Developers course.
C commonly rejects invalid input with an if followed by return. Swift guard expresses a precondition for the remaining scope, and its else branch must leave that scope through a control transfer such as return or throw. A failed guard cannot simply fall through.
The source tests null before reading the first byte, using short-circuit evaluation. Swift guard let establishes a nonoptional name and checks it is nonempty; the unwrapped binding remains available after the guard. The complete examples choose the rejected-empty path, while their success messages are independently defined.
C: complete program
main.c
#include <stdio.h>
#include <string.h>
static const char *announce(const char *room) {
if (room == NULL || room[0] == '\0') return "No room";
return "Room available";
}
int main(void) { puts(announce("")); return 0; }
Swift: complete program
Functions.swift
import Foundation
func announce(_ room: String?) -> String {
guard let name = room, !name.isEmpty else { return "No room" }
return "Room " + name
}main.swift
import Foundation
print(announce(""))A Swift if-let binding is confined to its success branch. A guard-let binding is available in the enclosing scope after the guard succeeds.
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