Skip to content
Swift

Structs and Classes

Compare value-type structs with reference-type classes and inheritance.

By EZ4Code Team
structclassvalue-type

Code

import Foundation

// Struct: value type
struct PointStruct {
    var x: Double
    var y: Double
    mutating func moveBy(dx: Double, dy: Double) {
        x += dx; y += dy
    }
}

// Class: reference type, supports inheritance and deinit
class Animal {
    let name: String
    init(name: String) { self.name = name }
    func speak() -> String { "\(name) makes a sound" }
    deinit { print("\(name) deinit") }
}

class Dog: Animal {
    override func speak() -> String { "\(name) says woof" }
}

// Value semantics: copy on assignment
var p1 = PointStruct(x: 1, y: 2)
var p2 = p1
p2.moveBy(dx: 10, dy: 10)
print(p1, p2)   // p1 unchanged

// Reference semantics: shared instance
let a = Dog(name: "Rex")
let b = a
print(a.speak(), b.speak())

// Equatable conformance
struct Money: Equatable {
    let amount: Double
    let currency: String
    static func == (l: Money, r: Money) -> Bool {
        l.amount == r.amount && l.currency == r.currency
    }
}
print(Money(amount: 5, currency: "USD") == Money(amount: 5, currency: "USD"))

Explanation

Structs are value types copied on assignment, making them safe for small immutable data. Classes are reference types that support inheritance, identity, and deinit for resource cleanup. Choose structs by default and reach for classes only when you need shared mutable state or subclassing.

More Swift Snippets