Guard and Early Exit
Lesson 8 of 48 in Coddy's Swift for Rust Developers course.
Rust let-else can bind a pattern on success while requiring the else branch to diverge, for example by returning. Swift guard let has a similar success-path role for optionals: its failure branch must leave the enclosing scope and the unwrapped binding remains available afterwards. A later guard can validate another condition. The source uses Option<i32>, and the target uses Int?, but both separate absent input from a present negative value. Keep a failure path distinct from normal computation rather than manufacturing a default that could be mistaken for valid input. The task has its own preconditions beyond this temperature description.
Rust
fn describe(value: Option<i32>) -> &'static str {
let Some(n) = value else { return "missing"; };
if n < 0 { return "frozen"; }
"liquid"
}
fn main() {
println!("{}", describe(None));
println!("{}", describe(Some(-2)));
}
Swift
func describe(_ value: Int?) -> String {
guard let n = value else { return "missing" }
guard n >= 0 else { return "frozen" }
return "liquid"
}
print(describe(nil))
print(describe(-2))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 Rust 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