Python Structures (struct), Value Semantics & Mutating Methods
Structs are the building blocks of idiomatic Swift (SwiftUI, Foundation types). Learn value semantics (copy-on-assignment), automatic memberwise initializers, mutating methods, and why Apple recommends defaulting to structs over classes.
"A struct is like an electronic spreadsheet file: when you email a copy to a colleague, they work on their own independent copy. Any edits they make never alter your original file."
Deep Dive: How It Works
Value Types: Assigning a struct to a new variable or passing it into a function creates an independent copy.
Memberwise Initializer: Swift generates an automatic constructor for structs based on their stored properties.
Mutating Methods: Methods on a struct that modify internal properties must be marked with the mutating keyword.
Copy-on-Write (CoW): Swift standard library collections (Array, Dictionary, String) are structs that copy storage only when mutated.
Syntax Blueprint
struct Point {
var x: Double
var y: Double
mutating func move(dx: Double) { x += dx }
}Define structs with stored properties and mark self-modifying functions with mutating.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Trying to call a mutating method on a struct instance declared with let.Why it happens: let freezes the entire struct value, preventing mutating methods from changing any internal property.
How to fix: Declare the struct instance with var if you need to invoke mutating methods.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Rectangle Struct with Area Method
Define a struct Rectangle with properties var width: Double and var height: Double.
Add a method area() -> Double returning width * height.
In top-level code, create a Rectangle with width 4.0 and height 5.0, and print "Area: \(rect.area())".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.