ExpressibleByArrayLiteral in Swift
When working with structs, you may encounter ExpressibleByArrayLiteral in a number of situations. It may seem obscure at first glance, but it’s helpful to know how it actually works and what it provides.
ExpressibleByArrayLiteral, as its very name signifies, is a protocol that allows the type it conforms to be initialized using an array literal. Additionally, it can increase readability. For clarity, you will examine this as a simple example.
Say, you’ve a Stack which its type is struct.
struct Stack<Element: Equatable>: Equatable {
/// Holds the stack data.
private var storage: [Element] = []
init() { }
}
When you initialize the Stack, you have to initialize like this:
let stack = Stack(["expressible", "by", "array", "literal"]
However, if you add ExpressibleByArrayLiteral extension to the Stack:
extension Stack: ExpressibleByArrayLiteral {
init(arrayLiteral elements: Element…) {
storage = elements
}
}
You could initialize the Stack like this:
let stack: Stack = ["expressible", "by", "array", "literal"]
The implementation is that simple! You can now try it out on your own project(s). You can access the GitHub repository where I used this here.
Thanks for reading!