Result as a Stored Outcome
Lesson 32 of 48 in Coddy's Swift for C Developers course.
C can represent a stored success or failure with an explicit tag and payload fields. The implementation must preserve agreement between the tag and meaningful data. Swift Result<Success, Failure> supplies typed success and failure cases, with Failure conforming to Error.
The examples store an offline load outcome rather than immediately raising or throwing. A caller can keep the result and inspect it later. Swift pattern matching binds the relevant associated value, while the C caller checks its tag before reading the success text. Returning a failure value does not itself transfer control to a catch handler.
C: complete program
load.h
#ifndef LOAD_H
#define LOAD_H
typedef enum { LOAD_OK, LOAD_OFFLINE } LoadKind;
typedef struct { LoadKind kind; const char *text; } Load;
#endif
loaded.h
#ifndef LOADED_H
#define LOADED_H
#include "load.h"
static inline Load loaded(const char *text) { return (Load){LOAD_OK, text}; }
#endif
unavailable.h
#ifndef UNAVAILABLE_H
#define UNAVAILABLE_H
#include "load.h"
static inline Load unavailable(void) { return (Load){LOAD_OFFLINE, 0}; }
#endif
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "loaded.h"
#include "unavailable.h"
int main(void) {
Load outcome = unavailable();
if (outcome.kind == LOAD_OK) puts(outcome.text); else puts("offline");
return 0;
}
Swift: complete program
LoadError.swift
import Foundation
enum LoadError: Error { case offline }main.swift
import Foundation
let outcome: Result<String, LoadError> = .failure(.offline)
switch outcome {
case .success(let text): print(text)
case .failure(.offline): print("offline")
}Optional carries presence or absence without an error payload. Choose Result when callers need a specific failure reason.
Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for C Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps7Failures and Abstraction
Throwing Functions and CatchResult as a Stored OutcomeProtocols and ConformanceExtensions Add BehaviorGeneric Value ContainersRecap: Validated Batch2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground