Enums as Finite Choices
Lesson 12 of 48 in Coddy's Swift for Python Developers course.
Python Enum creates named members whose values you choose. Swift enum cases also define a finite type, and exhaustive switching helps the compiler detect a missing case. Swift cases do not need raw values; add a raw type only when the program needs that representation.
When the expected enum type is known, Swift accepts a leading dot such as .compact. An enum can expose methods and computed properties, and those methods can switch on self. A method that changes an enum value needs mutating.
The example chooses a page margin from a layout mode. The exercise asks for transitions among another enum set, so use the same finite-choice mechanics while designing that transition yourself.
Complete Python comparison program:
from enum import Enum
class Layout(Enum):
COMPACT = 4
ROOMY = 12
choice = Layout.ROOMY
print(choice.value)Complete Swift comparison program, compiled from these files:
Layout.swift
enum Layout {
case compact, roomy
var margin: Int {
switch self {
case .compact: return 4
case .roomy: return 12
}
}
}main.swift
let choice: Layout = .roomy
print(choice.margin)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 Python 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