0
0
Swiftprogramming~20 mins

Collection slicing and indices in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Collection Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What is the output of slicing a Swift array with a range?

Consider the Swift array let numbers = [10, 20, 30, 40, 50]. What is the output of numbers[1..<4]?

Swift
let numbers = [10, 20, 30, 40, 50]
let slice = numbers[1..<4]
print(Array(slice))
A[10, 20, 30, 40]
B[20, 30, 40]
C[20, 30, 40, 50]
D[30, 40, 50]
Attempts:
2 left
💡 Hint

Remember that the range 1..<4 includes the start index but excludes the end index.

📝 Syntax
intermediate
2:00remaining
Which option correctly slices a Swift dictionary's keys?

Given let dict = ["a": 1, "b": 2, "c": 3, "d": 4], which code correctly slices the keys from index 1 to 3?

Swift
let dict = ["a": 1, "b": 2, "c": 3, "d": 4]
let keysSlice = ???
print(Array(keysSlice))
AArray(dict.keys)[1..<3]
Bdict.keys[1..<3]
Cdict.keys[1...3]
Ddict.keys[1,3]
Attempts:
2 left
💡 Hint

Dictionary keys are not directly indexable; you may need to convert them to an array first.

optimization
advanced
2:00remaining
Which slicing method is most efficient for large Swift arrays?

You have a large array let bigArray = Array(1...1000000). Which slicing method avoids copying elements and is most efficient?

Swift
let bigArray = Array(1...1000000)
let slice = ???
AbigArray[100...199]
BArray(bigArray[100..<200])
CbigArray.prefix(200).suffix(100)
DbigArray[100..<200]
Attempts:
2 left
💡 Hint

Consider which methods return slices without copying the underlying elements.

🔧 Debug
advanced
2:00remaining
Why does this Swift slice cause a runtime error?

Given let arr = [1, 2, 3], why does let slice = arr[1..<5] cause a runtime error?

Swift
let arr = [1, 2, 3]
let slice = arr[1..<5]
print(Array(slice))
ASlicing with range operator is not allowed on arrays.
BThe lower bound 1 is invalid for slicing.
CThe upper bound 5 is out of range for the array indices.
DThe array must be converted to a slice before slicing.
Attempts:
2 left
💡 Hint

Check the valid index range for the array.

🧠 Conceptual
expert
2:00remaining
How does Swift's Collection slicing preserve indices?

When slicing a Swift collection, how are the indices of the slice related to the original collection?

AThe slice uses the same indices as the original collection, preserving index values.
BThe slice resets indices starting from zero regardless of original indices.
CThe slice uses random indices unrelated to the original collection.
DThe slice uses string keys as indices instead of integers.
Attempts:
2 left
💡 Hint

Think about how Swift's ArraySlice works with indices.