Subscripting an Array with a Range

suggest change

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 is a subsequence of the array, and it keeps the original indices, so in this example slice.startIndex is 2 rather than 0.

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

An ArraySlice conforms to Collection (CollectionType in Swift 2) and can be used with sorted, filter, and similar methods. It is meant for a short computation, not for long-term storage. Convert it back to an Array when you are done.

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"]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents