swift
string-to-enum
enums
swift-programming
type-conversion

In Swift, is it possible to convert a string to an enum?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Yes, Swift can convert a string to an enum directly when the enum uses raw string values. This is a common pattern for parsing API payloads, command arguments, and local configuration flags. The safest approach is to combine raw value initialization with clear fallback handling.

Raw String Enums and Direct Conversion

Swift enums can conform to RawRepresentable automatically when you assign raw values. For string parsing, declare the enum as String backed and initialize it with init(rawValue:).

swift
1enum Environment: String {
2    case dev
3    case staging
4    case production
5}
6
7let input = "staging"
8if let env = Environment(rawValue: input) {
9    print("Parsed: \(env)")
10} else {
11    print("Unknown environment")
12}

This conversion is concise and type safe. You avoid hard coded string checks spread across the codebase, and compiler support makes refactoring safer.

Handling External Input Safely

Real input often includes case differences, whitespace, or alternate labels. Add a custom parsing layer that normalizes incoming text before attempting enum conversion.

swift
1enum Role: String {
2    case admin
3    case editor
4    case viewer
5
6    static func parse(_ raw: String) -> Role? {
7        let normalized = raw.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
8        switch normalized {
9        case "administrator":
10            return .admin
11        default:
12            return Role(rawValue: normalized)
13        }
14    }
15}
16
17print(Role.parse(" Admin ") as Any)
18print(Role.parse("administrator") as Any)

Centralizing this logic prevents subtle bugs where one code path trims text and another does not. It also gives you one place to support legacy terms during migrations.

Better Diagnostics and Defaults

Sometimes you need more than optional return values. You may want structured errors for logging or user feedback. A throwing parser communicates why parsing failed and can preserve the original value for diagnostics.

swift
1enum ParseError: Error {
2    case unsupportedValue(String)
3}
4
5enum Theme: String {
6    case light
7    case dark
8
9    static func required(_ raw: String) throws -> Theme {
10        let normalized = raw.lowercased()
11        guard let value = Theme(rawValue: normalized) else {
12            throw ParseError.unsupportedValue(raw)
13        }
14        return value
15    }
16}
17
18do {
19    let theme = try Theme.required("Light")
20    print(theme)
21} catch {
22    print("Failed to parse theme: \(error)")
23}

If business rules allow defaults, apply them in one boundary layer, not everywhere. That keeps fallback behavior explicit and auditable.

Codable Integration for API Payloads

Enum parsing becomes even cleaner when you integrate with Codable. Instead of hand parsing every field, define a model and let JSONDecoder map strings into enums. You still keep control by implementing custom decoding for better fallback behavior.

swift
1import Foundation
2
3enum Status: String, Codable {
4    case queued
5    case running
6    case done
7}
8
9struct Job: Codable {
10    let id: Int
11    let status: Status
12}
13
14let data = """
15{"id": 42, "status": "running"}
16""".data(using: .utf8)!
17
18let job = try JSONDecoder().decode(Job.self, from: data)
19print(job)

When payload values drift over time, keep a compatibility layer near decoding boundaries. Parse unknown strings intentionally, log them, and decide whether to reject or map them to a safe domain state. For client side apps, this is also a good place to instrument telemetry so product and backend teams can see which unexpected values are appearing in the field. That feedback loop helps you update enum cases deliberately instead of reacting to random crashes from unhandled strings.

Common Pitfalls

  • Assuming raw value parsing is case insensitive. It is strict unless you normalize first.
  • Handling enum parsing in many places, which leads to inconsistent alias support.
  • Returning defaults silently for every invalid value, which hides data quality issues.
  • Mixing transport strings and domain enums deep in business logic.
  • Forgetting to test unknown values, then crashing on new server responses.

Summary

  • Use string backed enums with init(rawValue:) for direct parsing.
  • Normalize external input before conversion.
  • Centralize alias and fallback logic in enum helpers.
  • Use throwing parsers when diagnostics matter.
  • Keep enum conversion at boundaries to protect domain logic.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.