Member-only story

Using Custom Strongly Typed Values For Better Coding in Swift

Discover ways to write safer and more comprehensive code.

Gabriel Theodoropoulos
5 min readMar 4, 2022
A picture of three links of an iron chain.
Photo by Edge2Edge Media on Unsplash

Not so long ago I discussed in this post about how to define enums with custom raw types in Swift. Creating enums with cases that can be either of a primitive data type, or a custom one as presented in that previous post, helps achieving a simple, yet quite important goal; to use values in our code that are strongly typed, instead of plain raw values. Doing so adds a lot to writing safer code, and avoid ambiguities and potential problems throughout the implementation process of an app.

Enum cases as custom strongly typed values

Say, for instance, that we have a variety of color values expressed as hexadecimal strings to use in various places around an app. Along with that, there’s also a hypothetical method that converts a hex string to an actual color supposedly named color(fromHex:). The simplest thing we could do in order to get an actual color would be to supply a hex string value as argument to that method:

--

--

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