Result as a Stored Outcome
Lesson 32 of 48 in Coddy's Swift for C++ Developers course.
Swift Result<Success, Failure> stores a typed outcome whose failure conforms to Error. C++17 can express such alternatives with std::variant and a dedicated error type; newer standard-library result facilities are a separate version choice. This example uses variant so its language baseline is explicit. The caller inspects a stored success instead of immediately catching an exception. Returning a failure alternative does not itself unwind control flow, although an accessor can have its own failure policy. Keep a successful empty string separate from lookup failure and choose the representation that preserves the information callers need.
C++
Complete program file: main.cpp.
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
struct Missing {};
using Lookup = std::variant<std::string, Missing>;
Lookup find_color(const std::string &key) {
if (key == "sky") return std::string("blue");
return Missing{};
}
int main() {
auto outcome = find_color("sky");
if (auto value = std::get_if<std::string>(&outcome)) std::cout << *value << '\n';
else std::cout << "missing\n";
}
Swift
Complete program file: LookupError.swift.
enum LookupError: Error { case missing }Complete program file: Functions.swift.
func findColor(_ key: String) -> Result<String, LookupError> {
key == "sky" ? .success("blue") : .failure(.missing)
}Complete program file: main.swift.
let outcome = findColor("sky")
switch outcome {
case .success(let value): print(value)
case .failure(.missing): print("missing")
}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