Structs & Enums
Structs and Enums are the building blocks of data modeling in Swift. Structs group related properties and behavior together, while enums define a group of related values.
Swift uses structs as its primary data type — even String, Int, and Array are structs under the hood.
Structs
A struct defines a blueprint for a custom data type with properties (data) and methods (behavior). Structs are value types — when you assign one to another variable, you get an independent copy.
Try it
Add a new property to the Recipe struct and update the describe() method to include it.
Enums
Enums define a type with a fixed set of related values. They can have raw values (like strings or integers) and associated values (custom data per case).
// Basic enum
enum Direction {
case north, south, east, west
}
// Enum with raw values
enum Planet: Int {
case mercury = 1
case venus = 2
case earth = 3
}
// Using switch
let direction = Direction.north
switch direction {
case .north: print("Going up")
case .south: print("Going down")
case .east: print("Going right")
case .west: print("Going left")
}
// Raw value access
let earthNumber = Planet.earth.rawValue // 3
Value Types vs Reference Types
- → Structs are value types — assigning copies the data. Each variable holds its own independent version.
- → Classes are reference types — assigning shares the same instance. Changes in one affect the other.
- → Swift favors structs for most data modeling because value semantics are safer and easier to reason about.
Quiz
Create a struct for a Recipe with name and ingredients properties, then create an instance and print its details.