Menu
CoddyTech

Result as a Stored Outcome

Lesson 32 of 48 in Coddy's Swift for PHP Developers course.

PHP can represent an outcome as an associative array with a tag and payload. The ordinary array declaration does not enforce a closed union between those shapes. A dedicated class hierarchy or static-analysis shape can make the contract more explicit, but consumers still need a coherent producer contract.

Swift Result<Success, Failure> packages success or failure in a checked enum, with Failure conforming to Error. A switch can inspect either case later. Merely receiving a Result is not a throwing call; its get() method is the operation that can throw the stored error.

The sample saves a failed lookup and handles it later. Swift Result makes those alternatives part of a generic enum type instead of an informal array convention. Choose returning a result when failure needs to travel as data, and throwing when control-flow propagation is the intended API.

Complete PHP comparison program:

<?php
declare(strict_types=1);
$cache = ["home" => "cached"];
$outcome = array_key_exists("help", $cache)
    ? ["kind" => "ok", "value" => $cache["help"]]
    : ["kind" => "error", "reason" => "missing"];
echo $outcome["kind"] === "ok" ? $outcome["value"] : "reload", "\n";

Complete Swift comparison program, compiled from these files:

CacheError.swift

enum CacheError: Error { case missing }

main.swift

let outcome: Result<String, CacheError> = .failure(.missing)
switch outcome {
case .success(let text): print(text)
case .failure: print("reload")
}
challenge icon

Challenge

Easy

Implement ParseError: Error with case invalid, and positive(_ text: String) -> Result<Int, ParseError>. Succeed only for a parsed integer strictly greater than zero; otherwise fail invalid. Input is one ASCII token of 1 through 8 digits or letters, optionally beginning with minus. Output ok:value or error. Values fit in Int.

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 ParseError.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 {
guard case .success(23) = positive("23"), case .failure(.invalid) = positive("0"), case .failure = positive("bad") else { return false }; return true
}
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 PHP Developers

Practice on your own: Swift playground