Menu
CoddyTech

Throwing Functions and Catch

Lesson 31 of 48 in Coddy's Swift for Lua Developers course.

Lua error raises an error, and pcall executes a function in protected mode. Its first result reports success; later results contain returned values or the error object. Lua errors are not restricted to a declared Error protocol, so an API must document the values it raises.

Swift throwing functions declare throws, and callers mark a throwing call with try. do/catch handles the error. try? converts failure into an optional result; it is useful when absence is enough information, but it discards the specific error. try! traps when an error is thrown.

The title operation rejects empty text and the caller prints a fallback. Protected calls and Swift catch both separate normal return from failure handling, but their syntax and result contracts differ. Preserve the task's required error type and cases rather than returning an arbitrary sentinel.

Complete Lua comparison program:

local function title(text)
  if text == "" then error("empty") end
  return string.upper(text)
end
local ok, result = pcall(title, "")
if ok then print(result) else print("missing title") end

Complete Swift comparison program, compiled from these files:

TitleError.swift

enum TitleError: Error { case empty }

Functions.swift

func title(_ text: String) throws -> String {
    if text.isEmpty { throw TitleError.empty }
    return text.uppercased()
}

main.swift

do {
    print(try title(""))
} catch {
    print("missing title")
}
challenge icon

Challenge

Easy

Implement DivisionError: Error with case zero, and quotient(_ numerator: Int, by denominator: Int) throws -> Int in Functions.swift. Throw zero for denominator 0; otherwise use integer division truncated toward zero. Input has two integers -1000 through 1000. Output the quotient or zero when this error is caught.

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 DivisionError.swift, Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
do { guard try quotient(17, by: 4) == 4 else { return false }; do { _ = try quotient(2, by: 0); return false } catch DivisionError.zero { } catch { return false }; return try quotient(-17, by: 4) == -4 } catch { return false }
}
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 Lua Developers

Practice on your own: Swift playground