What is the ExpressibleByIntegerLiteral Protocol in Swift?

Substitute your actual type with an Int

Zafar Ivaev
Clean Software

--

Photo by Christopher Burns on Unsplash

In this short article we will explore the ExpressibleByIntegerLiteral protocol in Swift based on a simple Xcode Playground example.

We generally use this protocol when we want to substitute our custom type with an Int. Using it in right situations helps you write more concise code.

Let’s Start

Say we have this simple struct called CustomNumber:

Now if we want to create an array of CustomNumbers we would write something like this:

How can we make it nicer? Let’s conform to the ExpressibleByIntegerLiteral protocol (notice that we no longer need the previous initializer):

--

--

Zafar Ivaev
Clean Software

Senior iOS Engineer. I write about features of Swift and iOS development practices.