Swift: OOP – code examples
Class with inheritance
Use case: Bundling data and behavior, e.g. users, products, game characters.
class Tier {
let name: String
init(name: String) { self.name = name }
func sprich() -> String { "\(name) makes a sound" }
}
class Hund: Tier {
override func sprich() -> String { "\(name) says Woof!" }
}
print(Hund(name: "Rex").sprich())Hund inherits from Tier and overrides sprich with override. For pure data, a struct (value type) is usually better.
Struct copies, class shares
OOP#struct#class#value semantics
Use case: Understanding why changes sometimes affect the copy and sometimes the original (models, UI state).
struct PunktS { var x = 0 }
class PunktK { var x = 0 }
var s1 = PunktS()
var s2 = s1
s2.x = 5
let k1 = PunktK()
let k2 = k1
k2.x = 5
print(s1.x, s2.x) // 0 5
print(k1.x, k2.x) // 5 5Value types (struct) are copied on assignment, reference types (class) are shared. This is the most important difference in everyday Swift.
Enum with associated values
OOP#enum#switch#state
Use case: Modeling states or results (loading state, commands, network response), with the compiler checking for completeness.
enum Ladezustand {
case leer
case laedt(fortschritt: Double)
case fertig(daten: [String])
case fehler(String)
}
func beschreibe(_ z: Ladezustand) -> String {
switch z {
case .leer: return "nothing loaded"
case .laedt(let f): return "loading \(Int(f * 100)) %"
case .fertig(let d): return "\(d.count) entries"
case .fehler(let m): return "Error: \(m)"
}
}
print(beschreibe(.laedt(fortschritt: 0.4)), beschreibe(.fertig(daten: ["a", "b"])))Each case carries exactly the data that makes sense there. If a case is missing from the switch, the compiler reports an error.