Discover CollectionOfOne
You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿
I want to show you a pretty interesting type in Swift called CollectionOfOne
!
Let’s see when this type can be useful…
You’ve probably been in the situation where you had to wrap a single value into an Array
, just to make your code work.
And you might have thought that, even though it wasn’t a big deal, it still felt a bit inefficient.
As it turns out, Swift actually has a special type just for this kind of situation.
So instead of wrapping the single value in an Array
, you can wrap it into a CollectionOfOne
.
Under the hood CollectionOfOne
is just a simple variable that also conforms to the protocol Collection
.
Which means that it’s a Collection
that can contain exactly one value, hence the name CollectionOfOne
.
Most of the time, the performance of your code will still be pretty much the same, whether you use an Array
or a CollectionOfOne
.
However, if your code is inside a tight loop with a big number of iterations, then you might get better performances when using CollectionOfOne
.
That’s all for this article, I hope you’ve enjoyed it!
Here’s the code if you want to experiment with it:
import Foundation
let someNumbers = [1, 2, 3]
let moreNumbers = someNumbers + CollectionOfOne(4)