Menu
CoddyTech

Guard and Early Exit

Lesson 8 of 48 in Coddy's Swift for JavaScript Developers course.

JavaScript commonly rejects an absent argument with an early if return. With no static parameter type in this program, callers must honor its intended string-or-undefined contract or the later method call can fail. Swift exposes the optional String contract in the function signature.

Swift guard let unwraps the value and makes the nonoptional binding available after the guard. Its else branch must leave the enclosing scope. This differs from an if-let binding restricted to its success branch. The examples reject absence and uppercase a present word; guard itself is not an exception handler.

JavaScript

Complete JavaScript console program:

main.js

function stem(file) {
  if (file === undefined) return "unselected";
  return file.toUpperCase();
}
console.log(stem(undefined));
console.log(stem("notes"));

Swift

Complete program; compile the listed files together:

Functions.swift

import Foundation
func stem(_ file: String?) -> String {
    guard let file else { return "unselected" }
    return file.uppercased()
}

main.swift

import Foundation
print(stem(nil))
print(stem("notes"))
challenge icon

Challenge

Easy

Implement 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") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for JavaScript Developers

Practice on your own: Swift playground