Guard and Early Exit
Lesson 8 of 48 in Coddy's Swift for Java Developers course.
Java often puts an early return in an if statement to reject missing input. Swift guard expresses the precondition of the remaining code. When its condition fails, the else block must leave the current scope, such as by returning or throwing.
An optional unwrapped in a successful guard stays available after the guard in its surrounding scope. Here a room announcement requires a nonempty room name. The Java method checks null before calling a method on the reference; Swift first unwraps the optional, then checks the string.
Java: complete program
Main.java
import java.util.*;
import java.util.function.*;
public class Main {
static String announce(String room) {
if (room == null || room.isEmpty()) return "No room";
return "Room " + room;
}
public static void main(String[] args) throws Exception {
System.out.println(announce(""));
}
}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 guard else block cannot fall through to the next statement. An if-let binding, unlike a guard-let binding, is limited to its success branch.
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 Java 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