← Back to list

Swift Rewind : The Fundamentals of Data Modeling

Season 3 — Episode 2: Enums Evolved — Unlocking Methods & Raw Values

Krishna Panchal · 2026-03-21 14:46 · 1 claps · 3.8 min read
#swift-programming #enumeration #enum #enums-in-swift #swift-rewind
Open on Medium ↗
Wiki topics: 💻 · Programming 📱 · Mobile Development 🔧 · Data Engineering

Swift Rewind : The Fundamentals of Data Modeling

Season 3 — Episode 2: Enums Evolved — Unlocking Methods & Raw Values

In Swift, an enumeration (enum) can have a raw value type. A raw value assigns a fixed value to each enum case.

When an enum is declared with a raw value type like Int, Swift automatically assigns values starting from 0. But we are not limited to the default values. We can explicitly assign raw values to each case.


enum TextAlignment: Int {
    case left // 0
    case right // 1
    case center // 2 
    case justify // 3
}

let alignment = TextAlignment.justify
print(alignment.rawValue)   // 3

// =======================================

enum TextAlignment: Int {
    case left = 20
    case right = 30
    case center = 40
    case justify = 50
}

📭 When Are Raw Values Useful? — when you need to store or transmit enum values to systems that don’t understand Swift enums. Example — APIs , Databases, JSON, UserDefaults. They also help avoid writing unnecessary conversion functions.

// ✅ Instead of writing a function to get the string representation, just use rawValue
enum Status: String {
    case success = "Success"
    case failure = "Failure"
    case pending = "Pending"
}

let currentStatus = Status.success

// Better Approach Using Raw Values - Swift automatically provides the string representation using .rawValue
print(currentStatus.rawValue) // "Success"

// 🚫 Writing a function
func statusToString(status: Status) -> String {
    switch status {
    case .success:
        return "Success"
    case .failure:
        return "Failure"
    case .pending:
        return "Pending"
    }
}

print(statusToString(status: currentStatus)) // Output: "Success"

📭 Converting Raw Values Back to Enum — If you already have a raw value and want to convert it back to an enum case, Swift provides a failable initializer.

enum TextAlignment: Int {
    case left = 20
    case right = 30
    case center = 40
    case justify = 50
}

let myRawValue = 20

// Convert raw value into a TextAlignment case using TextAlignment(rawValue:)
if let myAlignment = TextAlignment(rawValue: myRawValue) {
    print("Successfully created \(myAlignment) from \(myRawValue)")
} else {
    print("\(myRawValue) has no corresponding TextAlignment case")
}

// Output: - Successfully created left from 20

TextAlignment(rawValue:) returns an optional because the raw value may not match any enum case. If the value exists → conversion succeeds. If not → the result is nil.

📭 Raw Values with Strings — When an enum has a raw value type of String, Swift automatically assigns the case name as the raw value.

enum ProgrammingLanguage: String {
    case swift
    case objectiveC = "objective-c"
    case c
    case cpp = "c++"
    case java
}

let myFavoriteLanguage = ProgrammingLanguage.swift
print("My favorite programming language is \(myFavoriteLanguage.rawValue)")

// My favorite programming language is swift

🌟 Key Takeaways

Enums can have raw values (Int, String, etc.). Int enums automatically start from 0. You can customize raw values. Use .rawValue to access them. Use EnumName(rawValue:) to convert raw values back to enums. String enums automatically use the case name as the raw value.

Enum Methods

Enums in Swift can also have methods. A method inside an enum can use the enum’s current case (self) to perform logic. Methods let you attach behaviour directly to enum cases, making your code more organized and expressive.

enum LightBulb {
    case on
    case off

    func surfaceTemperature(forRoomTemperature room: Double) -> Double {
        // Inside the method, self refers to the current case (.on or .off)
        switch self {
        case .on:
            return room + 150.0
        case .off:
            return room
        }
    }
}

// bulb is an instance of LightBulb
let bulb = LightBulb.on
let roomTemperature = 77.0

// We call the method using: instance.methodName(arguments)
let bulbTemperature = bulb.surfaceTemperature(forRoomTemperature: roomTemperature)

// Lastly storing result of method call inside the variable and printing to console.
print("Bulb Temperature is \(bulbTemperature)")

Note: All Swift methods have a implicit argument named self, which is used to access the instance on which method is called — in this case, the instance of LightBulb.

  • If bulb = .on → temperature increases
  • If bulb = .off → temperature stays same

Understanding self argument on Enum methods

Inside enum methods, self refers to the current case of the enum. Sometimes, you may want to modify that case.

Problem: Modifying selfgives a compiler error

👉 Reason: Enums are value types, and by default, methods cannot modify self.

// Let’s add a method to toggle the bulb state:
func toggle() {
    switch self {
    case .on:
        self = .off
    case .off:
        self = .on
    }
}

✅ Solution: mutating Keyword — To allow changes to self, mark the method as mutating.

// Now the method can modify the enum’s value.
// Use mutating when your enum method needs to change its own state.
mutating func toggle() {
    switch self {
    case .on:
        self = .off
    case .off:
        self = .on
    }
}

var bulb = LightBulb.on
let roomTemperature = 77.0

var bulbTemperature = bulb.surfaceTemperature(forRoomTemperature: roomTemperature)
print("Bulb Temperature is \(bulbTemperature)")

// Using the toggle() Method
bulb.toggle()

bulbTemperature = bulb.surfaceTemperature(forRoomTemperature: roomTemperature)
print("Bulb Temperature is \(bulbTemperature)")

🌟 Key Takeaways

self refers to the current enum case. Enums are value types. By default methods on value types are not allowed to make changes to self. Use mutating to allow changes.

⭐️ You’ve just completed Episode 2 of Season 3:

In this episode, we explored how to use default and custom raw values in enums, convert them back to enum cases, and add behaviour using methods in enums (including mutating to change state).

Stay tuned — more calm, clear, and practical Swift concepts are coming next. Let’s keep rewinding Swift, one clean concept at a time.

💬 Found this helpful? Give this Medium post a like and share it with a fellow iOS developer revisiting Swift fundamentals.


메타데이터
post_id
feab3d04d958
slug
swift-rewind-the-fundamentals-of-data-modeling-feab3d04d958
url
https://medium.com/@krishhna.ios/swift-rewind-the-fundamentals-of-data-modeling-feab3d04d958
canonical_url
https://medium.com/@krishhna.ios/swift-rewind-the-fundamentals-of-data-modeling-feab3d04d958
author_url
https://medium.com/@krishhna.ios
status
ok
fetched_at
2026-06-16 19:09:56