Result as a Stored Outcome
Lesson 32 of 48 in Coddy's Swift for Kotlin Developers course.
Swift Result stores either a success value or a typed failure conforming to Error. Unlike a throwing call, a Result can be assigned, passed onward, and examined later without immediately unwinding control flow. Kotlin Result also models success or failure, but its failure uses Throwable rather than a separately declared generic error type. Swift switch can bind the payload of either case, and map transforms a successful value while leaving failure intact. Choose throws when a function should interrupt the current operation, and Result when an outcome is itself data your program needs to retain. The example transforms a successful unit value and separately inspects a stored failure.
Kotlin
fun main() {
val ok: Result<Int> = Result.success(4)
val bad: Result<Int> = Result.failure(IllegalStateException("offline"))
println(ok.map { it * 10 }.getOrDefault(-1))
println(bad.isFailure)
}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
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 Kotlin 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