Swift
Programming
Enumerations
Type Casting
Swift Language

Swift - Cast Int into enumInt

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Swift enums with a raw value type of Int can be initialized from an integer using init?(rawValue:), which returns an optional. The initializer returns nil if the integer does not match any case, making it safe by default. This is the primary mechanism for converting integers to enum values — there is no direct cast like in C or Objective-C.

Basic Conversion

swift
1enum Direction: Int {
2    case north = 0
3    case east = 1
4    case south = 2
5    case west = 3
6}
7
8// Int to enum — returns Optional
9let dir = Direction(rawValue: 2)
10print(dir)  // Optional(Direction.south)
11
12// Safe unwrapping
13if let direction = Direction(rawValue: 1) {
14    print("Direction: \(direction)")  // Direction: east
15}
16
17// Invalid value returns nil
18let invalid = Direction(rawValue: 99)
19print(invalid)  // nil

Force Unwrapping (When You're Certain)

swift
1// Only use when you guarantee the value is valid
2let dir = Direction(rawValue: 0)!
3print(dir)  // north
4
5// This crashes at runtime if the value is invalid
6// let crash = Direction(rawValue: 99)!  // Fatal error

Default Value with nil Coalescing

swift
1let input = 5  // Invalid value
2let direction = Direction(rawValue: input) ?? .north
3print(direction)  // north (default)
4
5// Common pattern for user input or API responses
6func handleDirection(_ value: Int) {
7    let dir = Direction(rawValue: value) ?? .north
8    print("Moving \(dir)")
9}

Enum to Int (Reverse)

swift
1let dir = Direction.south
2let value = dir.rawValue
3print(value)  // 2
4
5// Use in switch statements
6switch dir.rawValue {
7case 0: print("Going north")
8case 1: print("Going east")
9default: print("Other direction")
10}

Auto-Incrementing Raw Values

swift
1// Swift auto-increments from the first defined value
2enum Planet: Int {
3    case mercury = 1  // 1
4    case venus        // 2 (auto)
5    case earth        // 3 (auto)
6    case mars         // 4 (auto)
7}
8
9let earth = Planet(rawValue: 3)
10print(earth)  // Optional(Planet.earth)

If you omit the first raw value, it starts at 0:

swift
1enum Color: Int {
2    case red    // 0
3    case green  // 1
4    case blue   // 2
5}

Non-Sequential Raw Values

swift
1enum HTTPStatus: Int {
2    case ok = 200
3    case created = 201
4    case badRequest = 400
5    case unauthorized = 401
6    case notFound = 404
7    case serverError = 500
8}
9
10if let status = HTTPStatus(rawValue: 404) {
11    print("Status: \(status)")  // Status: notFound
12}
13
14// Gaps between values are fine
15let unknown = HTTPStatus(rawValue: 302)
16print(unknown)  // nil — 302 is not defined

Using with Switch

swift
1func describeDirection(_ value: Int) -> String {
2    guard let dir = Direction(rawValue: value) else {
3        return "Unknown direction"
4    }
5
6    switch dir {
7    case .north: return "Heading north"
8    case .east:  return "Heading east"
9    case .south: return "Heading south"
10    case .west:  return "Heading west"
11    }
12}
13
14print(describeDirection(1))   // "Heading east"
15print(describeDirection(99))  // "Unknown direction"

CaseIterable — Iterating All Cases

swift
1enum Direction: Int, CaseIterable {
2    case north = 0
3    case east = 1
4    case south = 2
5    case west = 3
6}
7
8// Iterate all cases
9for dir in Direction.allCases {
10    print("\(dir) = \(dir.rawValue)")
11}
12// north = 0, east = 1, south = 2, west = 3
13
14// Check if a value is valid without init
15let isValid = Direction.allCases.contains { $0.rawValue == 2 }
16print(isValid)  // true

Codable Enums with Int Raw Values

swift
1enum Priority: Int, Codable {
2    case low = 0
3    case medium = 1
4    case high = 2
5    case critical = 3
6}
7
8// JSON decoding
9let json = """
10{"priority": 2}
11""".data(using: .utf8)!
12
13struct Task: Codable {
14    let priority: Priority
15}
16
17let task = try JSONDecoder().decode(Task.self, from: json)
18print(task.priority)  // high
19
20// Encoding
21let encoded = try JSONEncoder().encode(task)
22print(String(data: encoded, encoding: .utf8)!)  // {"priority":2}

When an enum conforms to Codable and has an Int raw value, JSON encoding/decoding uses the raw value automatically.

Objective-C Interop

swift
1// @objc enums must have Int raw type
2@objc enum PlayerState: Int {
3    case stopped = 0
4    case playing = 1
5    case paused = 2
6}
7
8// In Objective-C, this becomes:
9// typedef NS_ENUM(NSInteger, PlayerState) { ... };
10
11// Convert from Objective-C integer
12let state = PlayerState(rawValue: 1)!  // playing

@objc enums are limited to Int raw values and cannot have associated values.

Common Pitfalls

  • Forgetting init?(rawValue:) returns Optional: The result is always Optional<EnumType>. Forgetting to unwrap leads to compiler warnings or unexpected behavior. Always use if let, guard let, or ??.
  • Force unwrapping unknown values: Direction(rawValue: userInput)! crashes if the input is invalid. Always validate external input with optional binding.
  • Assuming sequential raw values: After case a = 0, case b = 5, the next auto-incremented case is 6, not 2. Gaps in raw values mean some integers return nil.
  • String enums vs Int enums: enum Foo: String uses init?(rawValue: String), not Int. Make sure your enum's raw type matches what you are converting from.
  • Performance of init?(rawValue:): For enums with many cases, init?(rawValue:) may use a linear scan. If performance matters with hundreds of cases, consider a dictionary lookup instead.

Summary

  • Use EnumType(rawValue: intValue) to convert an integer to an enum — it returns an optional
  • Use .rawValue to convert an enum case back to its integer value
  • Swift auto-increments raw values from the last explicitly set value
  • Always handle the nil case (invalid integer) with if let, guard let, or ??
  • Enums with Int raw values work seamlessly with Codable and @objc
  • Use CaseIterable to iterate all cases or validate raw values

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.