Functional Snippet #8: Wrapper Types

Sometimes you want to distinguish two types from each other. For example, if you have user accounts with credits on them, you could have a function that asks the server for an account's credits:

								func credits(account: Account) -> Int


However, somewhere deeper in your code, you might see this Int and not know that it describes the number of credits. Therefore, it can be very helpful to add a typealias, so you can make the function return a value of type Credits:

								typealias Credits = Int

func credits(account: Account) -> Credits 


After doing this you can pass around values of type Credits. This turns out to be very useful when reading code: it is immediately clear what Credits is about. We can even take this one step further: let's assume that Credits come from the backend, and nowhere in our client code do we want to modify it. To prevent us from accidentally treating Credits as an Int, we could wrap it in a struct:

								struct Credits { let amount: Int }


The nice thing about this is that the compiler warns you when you try to do something like Credits(amount: 0) + 1 or even adding two values of Credits to each other. Wrapping a simple integer in a new type can prevent a lot of accidental mistakes. This is also very useful when dealing with things like currencies, physical units, and so on. You can also wrap other types: in many cases it might make sense to wrap a String type once and then use it in multiple places.

Stay up-to-date with our newsletter or follow us on Twitter .

Back to the Blog

Recent Posts