Structs in Swift: Properties, Methods, Initializers, mutating and Value Semantics
A First Struct
swift
struct Book {
var title: String
var pages: Int
var isRead = false
func summary() -> String { "\(title), \(pages) pages" }
}
var b = Book(title: "Swift Basics", pages: 200) // memberwise initializer
print(b.summary())
b.isRead = true
print(b.isRead)
Output
Swift Basics, 200 pages | true
A struct groups related data (properties) and actions (methods). Swift gives you a free memberwise initializer that takes all properties.
Computed Properties and mutating
swift
struct Rectangle {
var width: Double
var height: Double
var area: Double { width * height } // computed
mutating func scale(by factor: Double) { // changes self
width *= factor
height *= factor
}
}
var r = Rectangle(width: 3, height: 4)
print(r.area)
r.scale(by: 2)
print(r.width, r.height, r.area)
Output
12.0 | 6.0 8.0 48.0
Why mutating? Structs are value types, so a method that changes the struct must say so with
mutating. A let struct cannot call a mutating method.
Custom Initializers
swift
struct Temperature {
var celsius: Double
init(celsius: Double) { self.celsius = celsius }
init(fahrenheit: Double) { self.celsius = (fahrenheit - 32) * 5 / 9 }
}
print(Temperature(fahrenheit: 212).celsius)
Output
100.0
Value Semantics
When you assign a struct to another variable or pass it to a function, you get an independent copy. Changing one does not change the other.
swift
struct Point { var x: Int; var y: Int }
var a = Point(x: 1, y: 1)
var b = a
b.x = 99
print(a.x, b.x)
Output
1 99
When to Use a Struct
- Simple data: points, sizes, prices, settings, model objects
- Values that should be copied, not shared
- Most Swift standard types are structs, including
Int,String,ArrayandDictionary
Common Mistakes
- Forgetting
mutatingon a method that changes properties - Declaring a struct with
letand then trying to change it - Expecting a struct to be shared like a reference
Practice
- Create a
Studentstruct with a computedgradeproperty - Add a
mutatingmethod to add marks - Prove that copies are independent
Conclusion
Structs are Swift's default building block: simple, safe and copied by value.
Quick Summary: Properties; methods; init; mutating; value semantics.

