IntermediateLesson 8 of 16
Enums with Associated Values – Swift
Enums that carry data: modeling states safely.
Swift enums are much more powerful than in many other languages: each case can carry its own data (associated values), and enums may have methods and properties. Together with switch, this produces safe, readable state models.
enum Form {
case kreis(radius: Double)
case rechteck(breite: Double, hoehe: Double)
case punkt
func flaeche() -> Double {
switch self {
case .kreis(let r):
return Double.pi * r * r
case .rechteck(let b, let h):
return b * h
case .punkt:
return 0
}
}
}
print(Form.kreis(radius: 1).flaeche()) // 3.141592653589793
print(Form.rechteck(breite: 2, hoehe: 3).flaeche()) // 6.0Alternatively, cases get raw values (Int, String …). With CaseIterable you list all cases, and with init?(rawValue:) (returns an optional) you create cases from raw values.
enum Wochentag: Int, CaseIterable {
case montag = 1, dienstag, mittwoch
}
print(Wochentag.mittwoch.rawValue) // 3
print(Wochentag(rawValue: 2) == .dienstag) // true (init?(rawValue:) returns an optional)
print(Wochentag(rawValue: 9) == nil) // true (invalid raw value)
print(Wochentag.allCases.count) // 3
enum Richtung: String {
case nord, sued
}
print(Richtung.sued.rawValue) // suedWith if case and guard case you match a single case without writing a whole switch. Recursive data structures need indirect:
let s = Form.kreis(radius: 2)
if case .kreis(let radius) = s {
print("Radius", radius) // Radius 2.0
}
indirect enum Ausdruck {
case zahl(Int)
case plus(Ausdruck, Ausdruck)
case mal(Ausdruck, Ausdruck)
}
func werte(_ a: Ausdruck) -> Int {
switch a {
case .zahl(let n): return n
case .plus(let l, let r): return werte(l) + werte(r)
case .mal(let l, let r): return werte(l) * werte(r)
}
}
print(werte(.plus(.zahl(2), .mal(.zahl(3), .zahl(4))))) // 14TipThe best-known enum is
Optional itself: enum Optional<Wrapped> { case none; case some(Wrapped) }. Result<Success, Failure> is also an enum with associated values.WarningAn enum case like
.kreis(radius: 1) is not a subtype. There is only the type Form; you get the radius via pattern matching (case .kreis(let r)), not via dot access.