Member-only story

Creating Enums with Custom Raw Type in Swift

An additional way to use enums in Swift for smarter coding

Gabriel Theodoropoulos
5 min readFeb 11, 2022
Photo by Dominika Roseclay from Pexels

As developers who write code for the Apple ecosystem in Swift, we use enums all the time in order to represent lists of values that are meaningful to our programs. Enums can contain simple cases, but quite often there are raw values matching to each case. As an example, see the following that represents week days; each day has been assigned with an integer number starting from 1:

Enums with raw values just like the above are pretty handy in programming. We can easily get the raw value of a case using the rawValue property, as well as to get a case based on a raw value. And that is because an enum with raw values automatically conforms to RawRepresentable protocol once we declare the value type.

Usually, raw values are of basic Swift data types, such as Int, String, Double, etc. However, it’s absolutely possible to create enums with raw values of custom types as well. There are a couple of rules to follow in order to manage that, but nothing complicated or…

--

--

Gabriel Theodoropoulos
Gabriel Theodoropoulos

Written by Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev

No responses yet