Introduction
Collection slicing lets you take a part of a list or array easily. Indices help you find and use positions inside collections.
let slice = collection[startIndex..<endIndex] let index = collection.index(after: someIndex) let element = collection[index]
startIndex and endIndex to define the slice range.let numbers = [10, 20, 30, 40, 50] let slice = numbers[1..<4] print(slice)
let letters = ["a", "b", "c", "d"] let start = letters.startIndex let next = letters.index(after: start) print(letters[next])
let words = ["apple", "banana", "cherry", "date"] let range = words.indices.dropFirst().dropLast() for i in range { print(words[i]) }
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) }
index(after:) or index(before:) to move safely through indices.let numbers = [10, 20, 30, 40, 50]numbers[1...3] returns which part of the array?numbers[1...3] means take elements from index 1 to index 3, including both ends.items from index 2 to 5 (inclusive)?... includes both start and end indexes, so 2...5 means indexes 2, 3, 4, and 5.items[2..<5] uses half-open range which excludes index 5. items.slice(2, 5) calls a non-existent method. items[2,5] is invalid syntax. items[2...5] is correct.let fruits = ["apple", "banana", "cherry", "date", "fig"]let slice = fruits[1..<4]
print(slice)1..<4 includes indexes 1, 2, and 3 but excludes 4.let letters = ["a", "b", "c", "d"]
let slice = letters[1...4]1...4 tries to access index 4, which causes a runtime error.let data = [5, 10, 15, 20, 25, 30]1.. means indexes 1 up to but not including 5, which is indexes 1 to 4.Pass the test and this pattern moves unknown