CollectionOfOne in Swift

The Swift standard library includes a peculiar struct CollectionOfOne. It just represents a single value as a collection. Since it represents only a single value, then it is more efficient than creating an Array with a single element, which involves in allocating a buffer. Also, all the collection functions require inspecting the buffer whereas CollectionOfOne can hard-code many of these, like count which is always one. It can make a difference in performance critical code, but most of the time it does not make a real difference if we create a CollectionOfOne instance or an Array with one element.

let first = ["a", "b", "c"]
let second = CollectionOfOne("d")
print(first + second)
// ["a", "b", "c", "d"]
An example of appending a single element to an array.

If this was helpful, please let me know on Twitter @toomasvahter. Feel free to subscribe to RSS feed. Thank you for reading.