Enums as Finite Choices
Lesson 12 of 48 in Coddy's Swift for Rust Developers course.
Rust enums define a closed set of variants, but converting an arbitrary string into a variant needs an explicit parser or a suitable library-derived implementation. Integer discriminants are not an automatic general string mapping. Swift can declare a String raw-value enum and synthesizes a failable raw-value initializer. Mode(rawValue: "x") returns nil because no case has that representation. The Rust parser returns Option for the same reason. Keep the domain choice separate from its external representation, and do not assume every enum has a meaningful ordinal index. Associated-value enums are a separate way to store per-instance payload data.
Rust
enum Mode { Quiet, Loud }
impl Mode {
fn code(&self) -> &'static str { match self { Self::Quiet => "q", Self::Loud => "l" } }
fn parse(text: &str) -> Option<Self> {
match text { "q" => Some(Self::Quiet), "l" => Some(Self::Loud), _ => None }
}
}
fn main() {
println!("{}", Mode::Quiet.code());
println!("{}", Mode::parse("x").is_none());
}
Swift
enum Mode: String { case quiet = "q", loud = "l" }
print(Mode.quiet.rawValue)
print(Mode(rawValue: "x") == nil)Challenge
EasyImplement Signal.next() -> Signal and Signal.label: String in Signal.swift. Cases are red, green, amber. The cycle is red to green to amber to red, and label is the lowercase case name. Input is one case name; output the next label.
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 Signal.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 {
return Signal.red.next() == .green && Signal.green.next().next() == .red && Signal.amber.label == "amber"
}
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 Rust 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 Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry Rules3Control Flow
Switch and PatternsEnums as Finite ChoicesFor Loops and RangesWhile and Repeat LoopsRecap: Sequence ScanPractice on your own: Swift playground