Structures in Swift
Introduction to Structures in Swift
In Swift, a structure (struct) is a lightweight, efficient way to encapsulate related data and behavior. Unlike classes, structs are value types, meaning they are copied when assigned to a new variable or passed to a function.
Structures are highly optimized for performance and are recommended for most data models in Swift, especially when immutability and safety are priorities.
Why Use Structures in Swift?
- Value Semantics: Structs are copied, preventing unintended changes.
- Performance: Stored in the stack, making them faster than classes.
- Thread Safety: Safer in multithreading since copies are independent.
- Immutability: Encourages functional programming when used with
let
.
Class vs. Struct – Key Differences
Feature | Struct | Class |
---|---|---|
Type | Value | Reference |
Stored In | Stack | Heap |
Inheritance | No | Yes |
Deinitializer (deinit) | No | Yes |
Mutability | Immutable by default | Mutable |
Defining a Structure in Swift
struct StructName {
var property: Type
func method() {
// Code here
}
}
Example 1: Creating and Using a Struct
struct Car {
var brand: String
var model: String
var year: Int
func details() {
print("\(brand)
\(model) - Year: \(year)")
}
}
let myCar = Car(brand: "Tesla", model: "Model 3", year: 2024)
myCar.details()
Output
Example 2: Mutating a Struct Method
Since structs are immutable by default, use the mutating
keyword to modify properties.
struct Counter {
var count: Int = 0
mutating func increment() {
count += 1
}
}
var myCounter = Counter()
myCounter.increment()
print(myCounter.count) // 1
Output
Example 3: Structs with Computed Properties
struct Rectangle {
var width: Double
var height: Double
var area: Double {
return width * height
}
}
let rect = Rectangle(width: 10, height: 5)
print("Area: \(rect.area)")
Output
Example 4: Structs with Initializers
Swift structs automatically generate an initializer, but you can define a custom one.
struct Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let person1 = Person(name: "Alice", age: 25)
print(person1.name) // Alice
Output
Example 5: Value Type Behavior of Structs
struct Point {
var x: Int
var y: Int
}
var p1 = Point(x: 10, y: 20)
var p2 = p1 // Copy is created
p2.x = 30
print(p1.x) // 10 (Original remains unchanged)
print(p2.x) // 30 (Copy modified)
Output
30
Best Practices for Using Structs
- Use structs for simple data models that don’t need inheritance.
- Prefer structs over classes for thread-safe, predictable behavior.
- Use
mutating
functions to modify struct properties. - Avoid large structs (over 16 bytes) for performance optimization.
- Leverage value semantics to prevent unintended side effects.