Menu
Coddy logo textTech

Stride

Part of the Logic & Flow section of Coddy's Swift journey — lesson 8 of 56.

A range walks one step at a time. When you want a different step size, or to count down, use stride.

Two flavours: stride(from:to:by:) stops before the second value (half-open), stride(from:through:by:) may include it (closed):

for n in stride(from: 0, to: 10, by: 2) {
    print(n)
}
// 0, 2, 4, 6, 8
for n in stride(from: 10, through: 0, by: -2) {
    print(n)
}
// 10, 8, 6, 4, 2, 0

The by: argument must be the right sign: positive when counting up, negative when counting down. Mismatch and the loop runs zero times.

challenge icon

Challenge

Easy

Read three integers (three lines): start, end, step. The step may be positive or negative. The range is inclusive on both ends (use stride(from:through:by:)).

Print:

  1. The values in the stride, joined with ,
  2. The number of values produced

For input 0 / 10 / 3, the output is:

0,3,6,9
4

For input 10 / 0 / -2, the output is:

10,8,6,4,2,0
6

Cheat sheet

Use stride when you need a custom step size or to count down.

stride(from:to:by:) — half-open (excludes end value):

for n in stride(from: 0, to: 10, by: 2) { }
// 0, 2, 4, 6, 8

stride(from:through:by:) — closed (includes end value):

for n in stride(from: 10, through: 0, by: -2) { }
// 10, 8, 6, 4, 2, 0

The by: value must match the direction: positive when counting up, negative when counting down. A mismatch produces zero iterations.

Try it yourself

let start = Int(readLine()!)!
let end = Int(readLine()!)!
let step = Int(readLine()!)!

// TODO: stride(from:through:by:), join with comma, then print count
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow