Menu
Coddy logo textTech

Array Slicing Part 2

Part of the Fundamentals section of Coddy's Swift journey — lesson 74 of 86.

Swift provides convenient shorthand syntax for slicing from the beginning or to the end of an array. Instead of specifying 0 or the last index explicitly, you can leave one side of the range empty.

To slice from the start of an array up to a specific index, omit the starting value:

let numbers = [10, 20, 30, 40, 50]
let firstThree = numbers[..<3]
print(firstThree)  // [10, 20, 30]

Similarly, to slice from a specific index to the end, omit the ending value:

let numbers = [10, 20, 30, 40, 50]
let fromIndex2 = numbers[2...]
print(fromIndex2)  // [30, 40, 50]

You can also use the closed range version to include a specific starting point:

let letters = ["a", "b", "c", "d", "e"]
let upToIndex3 = letters[...3]
print(upToIndex3)  // ["a", "b", "c", "d"]

These one-sided ranges make your code cleaner when you need the first few elements or everything after a certain point. Remember to wrap the result in Array() if you need a regular array instead of an ArraySlice.

challenge icon

Challenge

Easy
Write a function splitArray that takes numbers and index and returns all elements from the given index to the end of the array.

Use the one-sided range operator (...) to slice from the specified index to the end, and return the result as a regular array.

Parameters:

  • numbers ([Int]): The array to slice
  • index (Int): The starting index (inclusive)

Returns: An array containing all elements from the given index to the end of the array ([Int])

Example: If numbers is [5, 10, 15, 20, 25, 30] and index is 3, the function should return [20, 25, 30].

Cheat sheet

Swift provides shorthand syntax for slicing arrays from the beginning or to the end by leaving one side of the range empty.

To slice from the start up to a specific index, omit the starting value:

let numbers = [10, 20, 30, 40, 50]
let firstThree = numbers[..<3]  // [10, 20, 30]

To slice from a specific index to the end, omit the ending value:

let numbers = [10, 20, 30, 40, 50]
let fromIndex2 = numbers[2...]  // [30, 40, 50]

Use the closed range version to include a specific ending index:

let letters = ["a", "b", "c", "d", "e"]
let upToIndex3 = letters[...3]  // ["a", "b", "c", "d"]

One-sided ranges return an ArraySlice. Wrap the result in Array() to convert it to a regular array:

let regularArray = Array(numbers[2...])

Try it yourself

func splitArray(numbers: [Int], index: Int) -> [Int] {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals