Safe collection subscripting in Swift

As many Swift developer before me, I wanted to find a way to easily fetch an Element from a Collection with its Index, without having to manually check if the Index I give is in the Collection’s bounds.

On internet, we can find here, here, here and somewhere here this solution, which consists to add a label to the subscript parameter.

With this extension, if you add the safe: label to your subscript it will return an Optional of your Element instead of the Element itself. Then, if the Index is in bounds, the Optional will embed your value, but if not, instead of a runtime error, you will get a .none Optional.

It does the job, but I really don’t like this label. It doesn’t feel natural at all to me.

How can we improve this to have a more “swifty” syntax ? Do we have something similar in the standard library ? Maybe Lazy Collections ? If Lazy Collections were impletemented like this labelled subscript feature above, we would have something like this :

But instead, we use a much clearer intermediate LazyCollection type like this :

So let’s build a SafeCollection type !

As you can see, it’s just a wrapper around your original collection, and it forwards subscript calls to its base only if given Index is in the collection bounds.

To use this collection like the lazy feature, we need to extend Collection.

Then we can use this new beautiful safe syntax like this :

(Updated to Swift 3 on November 22nd 2016 )

Show your support

Clapping shows how much you appreciated Jérôme Alves’s story.