Swift by Example: Structures
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
Resolution(width: 1920, height: 1080) uses the auto-generated memberwise initializer.var cinema = hd creates a copy of the struct, not a reference.cinema.width = 2048 modifies only the copy, leaving the original unchanged.mutating func moveBy allows the method to modify the struct's properties.
