Consider the Swift array let numbers = [10, 20, 30, 40, 50]. What is the output of numbers[1..<4]?
let numbers = [10, 20, 30, 40, 50] let slice = numbers[1..<4] print(Array(slice))
Remember that the range 1..<4 includes the start index but excludes the end index.
The slice numbers[1..<4] includes elements at indices 1, 2, and 3, which are 20, 30, and 40.
Given let dict = ["a": 1, "b": 2, "c": 3, "d": 4], which code correctly slices the keys from index 1 to 3?
let dict = ["a": 1, "b": 2, "c": 3, "d": 4] let keysSlice = ??? print(Array(keysSlice))
Dictionary keys are not directly indexable; you may need to convert them to an array first.
Dictionary keys are a collection but not indexable by integer ranges directly. Converting to an array allows slicing by integer indices.
You have a large array let bigArray = Array(1...1000000). Which slicing method avoids copying elements and is most efficient?
let bigArray = Array(1...1000000) let slice = ???
Consider which methods return slices without copying the underlying elements.
Using bigArray[100..<200] returns an ArraySlice which is a view and does not copy elements, making it efficient.
Given let arr = [1, 2, 3], why does let slice = arr[1..<5] cause a runtime error?
let arr = [1, 2, 3] let slice = arr[1..<5] print(Array(slice))
Check the valid index range for the array.
The array has indices 0 to 2. Using 5 as the upper bound exceeds the array's valid indices, causing a runtime error.
When slicing a Swift collection, how are the indices of the slice related to the original collection?
Think about how Swift's ArraySlice works with indices.
Swift slices preserve the original collection's indices, so the slice's indices match the original collection's indices for the sliced elements.