Swift - Cast Int into enumInt
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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
Force Unwrapping (When You're Certain)
Default Value with nil Coalescing
Enum to Int (Reverse)
Auto-Incrementing Raw Values
If you omit the first raw value, it starts at 0:
Non-Sequential Raw Values
Using with Switch
CaseIterable — Iterating All Cases
Codable Enums with Int Raw Values
When an enum conforms to Codable and has an Int raw value, JSON encoding/decoding uses the raw value automatically.
Objective-C Interop
@objc enums are limited to Int raw values and cannot have associated values.
Common Pitfalls
- Forgetting
init?(rawValue:)returns Optional: The result is alwaysOptional<EnumType>. Forgetting to unwrap leads to compiler warnings or unexpected behavior. Always useif 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 is6, not2. Gaps in raw values mean some integers returnnil. - String enums vs Int enums:
enum Foo: Stringusesinit?(rawValue: String), notInt. 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
.rawValueto convert an enum case back to its integer value - Swift auto-increments raw values from the last explicitly set value
- Always handle the
nilcase (invalid integer) withif let,guard let, or?? - Enums with
Intraw values work seamlessly withCodableand@objc - Use
CaseIterableto iterate all cases or validate raw values
Related reading
- Swift - Cast Int into enumInt
- Swift - check if a timestamp is yesterday, today, tomorrow, or X days ago
- Swift - check if a timestamp is yesterday, today, tomorrow, or X days ago
- Swift - class method which must be overridden by subclass
- Swift - Convert to absolute value
- Swift - Convert to absolute value
- Swift - encode URL
- Swift - encode URL
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.