avatarZafar Ivaev

Summary

The ExpressibleByIntegerLiteral protocol in Swift allows developers to substitute their custom type with an Int, making the code more concise and readable.

Abstract

In this article, we explore the ExpressibleByIntegerLiteral protocol in Swift using a simple Xcode Playground example. This protocol is useful when we want to replace our custom type with an Int. By conforming to this protocol, we can create arrays of custom types in a more elegant way. Additionally, we can add more flexibility by conforming to the ExpressibleByStringLiteral protocol, allowing us to use String values as well. There are several similar protocols available in Swift to suit various needs.

Bullet points

  • The ExpressibleByIntegerLiteral protocol in Swift is used to substitute custom types with an Int.
  • Using this protocol in the right situations can help write more concise code.
  • Conforming to the ExpressibleByIntegerLiteral protocol allows creating arrays of custom types in a more elegant way.
  • Conforming to the ExpressibleByStringLiteral protocol adds more flexibility, allowing the use of String values.
  • There are several similar protocols available in Swift to suit various needs.

What is the ExpressibleByIntegerLiteral Protocol in Swift?

Substitute your actual type with an Int

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):

We can now create that array in a much nicer way:

Which correctly prints out each member of our array:

We can add even more flexibility by conforming to an ExpressibleByStringLiteral , so we could also use String values:

There are lots of similar protocols available to suit your needs:

Wrapping Up

Interested in more lesser-known features of Swift? Feel free to check out my other relevant pieces:

Thanks for reading!

Swift
Programming
iOS
Mobile
Xcode
Recommended from ReadMedium