How to get enum from raw value in Swift?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
To create a Swift enum case from a raw value, use the failable initializer init?(rawValue:) — for example, MyEnum(rawValue: "some_value"). This returns an optional (MyEnum?) because the raw value may not match any case. Swift automatically synthesizes this initializer for any enum that declares a raw value type (String, Int, Double, etc.). If the value matches a case, you get the enum instance; otherwise you get nil.
Basic Usage
Integer Raw Values
String Enums with Implicit Raw Values
When the raw value type is String and no explicit values are assigned, Swift uses the case name as the raw value:
Handling the Optional Result
Since init?(rawValue:) is failable, you need to handle the nil case:
CaseIterable for Validation
Use CaseIterable to list all valid values or build lookup logic:
Codable Enums with Raw Values
Raw-value enums automatically conform to Codable when their raw type is Codable:
Custom Raw Value Mapping
When API values do not match your Swift naming conventions:
Enums Without Raw Values (Associated Values)
Enums with associated values do not have init?(rawValue:). You need a custom initializer:
Common Pitfalls
- Raw value matching is case-sensitive for strings:
Color(rawValue: "Red")returnsnilif the case is defined ascase red. Always normalize input (e.g.,.lowercased()) before matching, or useCaseIterablewith a custom case-insensitive lookup. - Forgetting that
init?(rawValue:)returns an optional: Force-unwrapping without checking (MyEnum(rawValue: input)!) crashes at runtime if the value is invalid. Always useif let,guard let, or nil-coalescing (?? .default) to handle thenilcase safely. - Assuming associated-value enums have raw values: Only enums with a declared raw value type (
enum Foo: String) get the synthesizedinit?(rawValue:). Enums with associated values (case bar(Int)) cannot have raw values — use a custom initializer or static factory method. - Not specifying explicit raw values when API format differs: If your API sends
"SUPER_ADMIN"but you definecase superAdminwithout an explicit raw value, Swift assigns"superAdmin"as the raw value. Always assign explicit raw values when the external format differs from Swift naming conventions. - Decoding errors crashing the app: When decoding JSON into a raw-value enum, an unrecognized value throws
DecodingError. Either handle the error withtry?, provide a default case in a custominit(from:), or validate the input before decoding.
Summary
- Use
MyEnum(rawValue: value)to create an enum from a raw value — it returns an optional - Swift auto-synthesizes
init?(rawValue:)for enums withString,Int, orDoubleraw types - Handle the
nilcase withif let,guard let, or nil-coalescing (?? .default) - Raw-value enums automatically conform to
Codablefor seamless JSON encoding/decoding - For associated-value enums, write a custom initializer since
init?(rawValue:)is not available
Related reading
- How to get hosting Activity from a view?
- How to get input value from a UIAlertController text field?
- How to get input value from a UIAlertController text field?
- How to get iOS device's WiFi IP address?
- How to get Latitude and Longitude of the mobile device in android?
- How to get mathemical PI constant in Swift
- How to get my IP address programmatically on iOS/macOS?
- How to get RGB values from UIColor?
.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.