Structs in Swift

From the Swift cheat sheet · Structs & Classes · verified Jul 2026

Structs

Value types with properties and methods

swift
// Struct definition
struct Point {
    var x: Double
    var y: Double

    // Computed property
    var magnitude: Double {
        return sqrt(x * x + y * y)
    }

    // Method
    func distance(to point: Point) -> Double {
        let dx = x - point.x
        let dy = y - point.y
        return sqrt(dx * dx + dy * dy)
    }

    // Mutating method
    mutating func moveBy(x deltaX: Double, y deltaY: Double) {
        x += deltaX
        y += deltaY
    }
}

// Usage
var point = Point(x: 3, y: 4)
print(point.magnitude)  // 5.0
point.moveBy(x: 1, y: 2)
💡 Structs are value types - copied when assigned
⚡ Use mutating keyword to modify struct properties
📌 Structs get memberwise initializers automatically
🟢 Prefer structs over classes for simple data models

More Swift tasks

Back to the full Swift cheat sheet