🐦 Swift

Structs & Enums

Lesson 3 of 5 ~6 min

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.

Editor
Swift
Output

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

Quiz

Are structs value types or reference types in Swift?
Challenge

Create a struct for a Recipe with name and ingredients properties, then create an instance and print its details.