Swift Language Arrays Subscripting an Array with a Range


Example

One can extract a series of consecutive elements from an Array using a Range.

let words = ["Hey", "Hello", "Bonjour", "Welcome", "Hi", "Hola"]
let range = 2...4
let slice = words[range] // ["Bonjour", "Welcome", "Hi"]

Subscripting an Array with a Range returns an ArraySlice. It's a subsequence of the Array.

In our example, we have an Array of Strings, so we get back ArraySlice<String>.

Although an ArraySlice conforms to CollectionType and can be used with sort, filter, etc, its purpose is not for long-term storage but for transient computations: it should be converted back into an Array as soon as you've finished working with it.

For this, use the Array() initializer:

let result = Array(slice)

To sum up in a simple example without intermediary steps:

let words = ["Hey", "Hello", "Bonjour", "Welcome", "Hi", "Hola"]
let selectedWords = Array(words[2...4]) // ["Bonjour", "Welcome", "Hi"]