Enums as Finite Choices
Lesson 12 of 48 in Coddy's Swift for JavaScript Developers course.
JavaScript strings can act as informal tags, but this function accepts any runtime value until its explicit switch validates the supported spellings. A frozen object of named constants can improve naming without creating a closed static enum type. Swift enum cases directly define a finite set of alternatives.
The source throws for an unknown format instead of silently treating it as rich. Swift can switch exhaustively on the enum without a default, exposing unhandled additions during compilation. Raw values are optional representations; an enum can also supply computed properties and methods independently of its declaration order.
JavaScript
Complete JavaScript console program:
main.js
function suffix(format) {
switch (format) {
case "plain": return "txt";
case "rich": return "rtf";
default: throw new Error("unknown format");
}
}
console.log(suffix("rich"));
Swift
Complete program; compile the listed files together:
Format.swift
import Foundation
enum Format {
case plain, rich
var suffix: String {
switch self {
case .plain: return "txt"
case .rich: return "rtf"
}
}
}main.swift
import Foundation
let format = Format.rich
print(format.suffix)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 JavaScript 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