0
0
Swiftprogramming~5 mins

Collection slicing and indices in Swift

Choose your learning style9 modes available
Introduction
Collection slicing lets you take a part of a list or array easily. Indices help you find and use positions inside collections.
You want to get a few items from a list without copying the whole list.
You need to check or change items between two positions in a collection.
You want to loop over just a part of a collection.
You want to find the position of an item to use it later.
You want to safely access elements without errors by using indices.
Syntax
Swift
let slice = collection[startIndex..<endIndex]
let index = collection.index(after: someIndex)
let element = collection[index]
Use startIndex and endIndex to define the slice range.
Indices are used to access or move through collection elements safely.
Examples
This gets elements from position 1 up to (but not including) 4, so 20, 30, 40.
Swift
let numbers = [10, 20, 30, 40, 50]
let slice = numbers[1..<4]
print(slice)
Finds the index after the first and prints the element at that position, which is 'b'.
Swift
let letters = ["a", "b", "c", "d"]
let start = letters.startIndex
let next = letters.index(after: start)
print(letters[next])
Loops over the middle elements, skipping the first and last.
Swift
let words = ["apple", "banana", "cherry", "date"]
let range = words.indices.dropFirst().dropLast()
for i in range {
  print(words[i])
}
Sample Program
This code slices the fruits array from position 1 to 3 and prints each fruit in that slice.
Swift
let fruits = ["apple", "banana", "cherry", "date", "elderberry"]
let start = fruits.index(fruits.startIndex, offsetBy: 1)
let end = fruits.index(fruits.startIndex, offsetBy: 4)
let slice = fruits[start..<end]
for fruit in slice {
  print(fruit)
}
OutputSuccess
Important Notes
Slicing a collection does not copy elements; it creates a view into the original collection.
Always ensure your indices are valid to avoid runtime errors.
Use index(after:) or index(before:) to move safely through indices.
Summary
Collection slicing extracts parts of a collection using index ranges.
Indices help you find and access elements safely.
Use slicing and indices to work efficiently with parts of collections.