Menu
CoddyTech

Result as a Stored Outcome

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

Rust Result<T, E> and Swift Result<Success, Failure> both store an outcome as a value. Swift requires Failure to conform to Error, while Rust's Result itself places no std::error::Error bound on E. Map transforms a success and preserves a failure without calling the success closure. Rust may move payloads when consuming a result; borrow-oriented methods can retain access when needed. Swift uses its value and reference semantics instead of the same move rules. Merely receiving a Result is not a throwing call in Swift, although get() can throw its failure. Both examples preserve the offline failure and transform four into forty.

Rust

enum LinkError { Offline }

fn main() {
    let ok: Result<i32, LinkError> = Ok(4);
    let bad: Result<i32, LinkError> = Err(LinkError::Offline);
    println!("{}", ok.map(|value| value * 10).unwrap_or(-1));
    println!("{}", bad.is_err());
}

Swift

enum LinkError: Error { case offline }
let ok: Result<Int, LinkError> = .success(4)
let bad: Result<Int, LinkError> = .failure(.offline)
if case .success(let value) = ok.map({ $0 * 10 }) { print(value) }
if case .failure = bad { print(true) }
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 Rust Developers

Practice on your own: Swift playground