SwSwift
IntermediateLesson 7 of 16

Structs vs. Classes – Swift

Value types and reference types, methods, computed properties, and inheritance.

Swift has two ways to define your own types: struct (value type: copied on assignment) and class (reference type: all variables point to the same object). Int, String, Array, and Optional are also structs or enums; the standard library is built predominantly from value types.

struct Punkt { var x: Int; var y: Int }

var a = Punkt(x: 1, y: 2)
var b = a               // copy
b.x = 99
print(a.x, b.x)         // 1 99

class Zaehler {
    var wert = 0
    func increment() { wert += 1 }
}
let z1 = Zaehler()
let z2 = z1             // same instance
z2.increment()
print(z1.wert)          // 1
print(z1 === z2)        // true (identity)

Structs automatically get a memberwise initializer (Punkt(x:y:)). Methods that modify a struct instance must be mutating. Computed properties and observers (didSet) make properties “alive”.

struct Rechteck {
    var breite: Double
    var hoehe: Double

    var flaeche: Double { breite * hoehe }       // computed property

    mutating func skaliere(um faktor: Double) {
        breite *= faktor
        hoehe *= faktor
    }
}

var r = Rechteck(breite: 3, hoehe: 4)
print(r.flaeche)          // 12.0
r.skaliere(um: 2)
print(r.flaeche)          // 48.0

struct Fortschritt {
    var prozent = 0 {
        didSet { print("from \(oldValue) to \(prozent)") }
    }
}
var f = Fortschritt()
f.prozent = 50            // from 0 to 50

Only classes support inheritance, deinitializers (deinit), and identity. With override you override methods, and final forbids overriding. Classes need their own initializer for properties without a default value.

class Tier {
    let name: String
    init(name: String) { self.name = name }
    func sprich() -> String { "\(name) makes a sound" }
}

final class Hund: Tier {
    override func sprich() -> String { "\(name) says Woof!" }
}

let tiere: [Tier] = [Tier(name: "Something"), Hund(name: "Rex")]
for t in tiere { print(t.sprich()) }
// Something makes a sound
// Rex says Woof!
TipApple's rule of thumb: Start with struct. Use class when you need shared mutable identity (e.g. a shared model), inheritance from Apple frameworks (UIKit classes), or Objective-C interop.
Warninglet on a class only protects the reference: let z = Zaehler(); z.wert = 5 is allowed. On a struct, let means true immutability: let p = Punkt(...); p.x = 1 does not compile.