ArraySlicing in Swift: Cannot subscript value of type

I’ve been seeing the above error on and off for a while now when returning an ArraySlice from a function. Every single time I solve it, I fail to make a mental note of the issue and struggle to recall why the compiler is giving me such an inaccurate error. Here’s an example that causes the error:

This function takes a String -> Int dictionary, and provides an array of 5 of its (key, value) tuples sorted by the value (which is an integer). For this code, LLVM will provide the slightly unhelpful error of Cannot subscript value of type [(String, Int)].

What it’s actually trying, and failing, to tell you is that you’ve simply specified an Array as the return type, and yet are providing an ArraySlice due to the slicing operator. You can verify this by simply replacing the above by:

Now we get the more helpful error of Cannot convert return expression of type ArraySlice<(String, Int)> to return type [(String, Int)]. The solution now is rather obvious: just explicitly cast.

I can understand the lack of implicit conversion from a slice to a full-blown array: developers would get lazy and would end up routinely negating the performance benefits of just slicing into arrays. I can’t help but feel however that the compiler should really provide the latter error message in both cases.

Leave a Reply