Recall & Review
beginner
What does the
stride(from:to:by:) function do in Swift?It creates a sequence of values starting from a given number, going up to (but not including) another number, stepping by a custom amount each time.
Click to reveal answer
intermediate
How is
stride(from:through:by:) different from stride(from:to:by:)?stride(from:through:by:) includes the end value in the sequence if it matches a step, while stride(from:to:by:) stops before reaching the end value.Click to reveal answer
beginner
Write a Swift code snippet using
stride(from:to:by:) to print even numbers from 2 up to 10 (excluding 10).for number in stride(from: 2, to: 10, by: 2) {
print(number)
}
// Output: 2 4 6 8
Click to reveal answer
intermediate
Can
stride be used with negative steps? Give an example.Yes, you can use negative steps to count down. Example:
for number in stride(from: 10, to: 0, by: -2) {
print(number)
}
// Output: 10 8 6 4 2
Click to reveal answer
beginner
Why might you choose
stride over a traditional for-in loop with a range?Because
stride lets you control the step size, including skipping numbers or counting backwards, which a simple range loop can't do directly.Click to reveal answer
What will
stride(from: 1, to: 5, by: 2) produce?✗ Incorrect
The sequence starts at 1, steps by 2, and stops before 5, so it includes 1 and 3 only.
Which function includes the end value if it matches the step exactly?
✗ Incorrect
stride(from:through:by:) includes the end value if it fits the stepping pattern.What happens if you use a negative step with
stride(from:to:by:) but the start is less than the end?✗ Incorrect
If the step direction doesn't match the start and end order, the sequence is empty.
How would you print numbers from 10 down to 2 stepping by 2 using stride?
✗ Incorrect
You need to start at 10, go down to 2, stepping by -2.
Which of these is NOT a valid use of stride in Swift?
✗ Incorrect
Step size cannot be zero; it would cause an error.
Explain how to use
stride to create a sequence with a custom step size and why it might be useful.Think about how you count in steps bigger than 1 or backwards.
You got /5 concepts.
Describe the difference between
stride(from:to:by:) and stride(from:through:by:) with examples.One stops before the end, the other can include it.
You got /3 concepts.