Guard and Early Exit
Lesson 8 of 48 in Coddy's Swift for R Developers course.
An R function can return early before its final expression. This function assumes one nonmissing string, checks its content and then uses one-based substring positions. R substring character handling is not a guarantee of extended-grapheme-cluster segmentation for combined Unicode text.
Swift guard requires its condition to succeed for execution to continue. Its else branch must exit the enclosing scope. guard let unwraps an optional and makes the new binding available after the guard, whereas an if let binding is scoped to its successful branch.
Swift String.first returns an optional Character and guard let leaves the successful binding available after the early exit. The ASCII sample keeps both first-character results simple. Validate the task's own input contract instead of generalizing this scalar helper to every possible R vector.
Complete R comparison program:
initial <- function(text) {
if (!nzchar(text)) return("missing")
substr(text, 1L, 1L)
}
cat(initial("birch"), "\n", initial(""), "\n", sep = "")
Complete Swift comparison program, compiled from these files:
Functions.swift
func initial(_ text: String) -> String {
guard let first = text.first else { return "missing" }
return String(first)
}main.swift
print(initial("birch"))
print(initial(""))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 R 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