Menu
CoddyTech

Result as a Stored Outcome

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

A Swift Result<Success, Failure> stores success or failure as an ordinary value; its failure type conforms to Error. This is useful when the outcome must be kept or passed onward instead of immediately throwing. C# often uses a custom result class or a Try method with an output parameter for similar APIs; those conventions are not automatically equivalent to Swift Result. Here a lookup returns a stored color label or a missing-key error. Pattern matching extracts the associated success value. A failure is still a value until you choose an operation such as get() that throws it. Keep lookup failure distinct from a successful empty string.

C#

Complete program file: Program.cs.

using System;
using System.Collections.Generic;
using System.Linq;
sealed class Lookup { public bool Success { get; private set; } public string Value { get; private set; } public Lookup(bool success, string value) { Success = success; Value = value; } }
static class Palette { public static Lookup Find(string key) { return key == "sky" ? new Lookup(true, "blue") : new Lookup(false, ""); } }

class Program
{
    static void Main()
    {
        var outcome = Palette.Find("sky");
        Console.WriteLine(outcome.Success ? outcome.Value : "missing");
    }
}

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 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 C# Developers

Practice on your own: Swift playground