BudiBadu Logo
Samplebadu

Swift by Example: Structures

Swift 5.x

Explore Swift structures with this code example illustrating value type semantics, automatic memberwise initializers, copy-on-assignment behavior, property declarations, and mutating methods that modify struct properties requiring the mutating keyword.

Code

struct Resolution {
    var width = 0
    var height = 0
}

// Memberwise initializer is automatically generated
let hd = Resolution(width: 1920, height: 1080)

var cinema = hd
cinema.width = 2048

print("Cinema width: (cinema.width)") // 2048
print("HD width: (hd.width)")         // 1920 (Original is unchanged)

// Mutating methods
struct Point {
    var x = 0.0, y = 0.0
    mutating func moveBy(x deltaX: Double, y deltaY: Double) {
        x += deltaX
        y += deltaY
    }
}

Explanation

Structures (structs) are similar to classes in that they can have properties and methods. However, the key difference is that structs are value types. When you assign a struct to a variable or pass it to a function, the value is copied. Modifying the copy does not affect the original.

Swift automatically generates a "memberwise initializer" for structs, allowing you to initialize member properties by name without writing a custom init method. This makes structs very convenient for simple data containers.

By default, methods in a struct cannot modify the struct's properties. To allow a method to modify the struct (mutate self), you must mark the method with the mutating keyword. This is not required in classes because classes are reference types.

Code Breakdown

7
Resolution(width: 1920, height: 1080) uses the auto-generated memberwise initializer.
9
var cinema = hd creates a copy of the struct, not a reference.
10
cinema.width = 2048 modifies only the copy, leaving the original unchanged.
18
mutating func moveBy allows the method to modify the struct's properties.