Menu
CoddyTech

Guard and Early Exit

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

Kotlin often handles invalid state with an early return from an if branch or an Elvis expression. Swift guard makes the success path explicit: its else branch must leave the current scope, for example with return or throw. A value unwrapped by guard let remains available after the guard, which keeps the main path less nested than an if-let block. Multiple comma-separated conditions must all hold. Guard is useful inside functions and loops, not a replacement for every conditional expression. The example obtains an optional temperature and then applies a separate freezing test; the task uses the same control-flow construct for a different contract.

Kotlin

fun describe(value: Int?): String {
    val n = value ?: return "missing"
    if (n < 0) return "frozen"
    return "liquid"
}
fun main() { println(describe(null)); println(describe(-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 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 Kotlin Developers

Practice on your own: Swift playground