Result as a Stored Outcome
Lesson 32 of 48 in Coddy's Swift for Dart Developers course.
Dart APIs may return a sealed outcome type when failure should be data, rather than throwing immediately. Swift provides Result<Success, Failure> with success and failure cases, and its failure type conforms to Error. A returned result does not throw merely because it is a failure. Switch over it to inspect the stored outcome, or call its throwing get() when exception-style propagation is desired. This example stores a missing-file outcome and handles it later. The Dart sealed hierarchy supplies the corresponding explicit alternatives.
Complete Dart program. Each labelled block is a separate file.
Outcome.dart
sealed class Outcome {}
final class Loaded extends Outcome {
final String text;
Loaded(this.text);
}
final class Missing extends Outcome {}main.dart
import 'Outcome.dart';
void main() {
final Outcome outcome = Missing();
switch (outcome) {
case Loaded(:final text): print(text);
case Missing(): print('not found');
}
}Complete Swift program. Each labelled block is a separate file.
LoadError.swift
import Foundation
enum LoadError: Error { case missing }main.swift
import Foundation
let outcome: Result<String, LoadError> = .failure(.missing)
switch outcome {
case .success(let text): print(text)
case .failure: print("not found")
}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 Dart 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