Menu
Coddy logo textTech

Range Methods

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

Ranges are real Collections, so they come with the same toolbox you use on arrays.

contains, count, first, and last all work directly:

let r = 1...10
print(r.contains(5))            // true
print(r.count)                  // 10
print(r.first!, r.last!)        // 1 10

Most array methods you've used work too. filter returns an array because the result of filtering a range isn't itself a range:

let evens = (1...10).filter { $0 % 2 == 0 }
print(evens)                    // [2, 4, 6, 8, 10]

Same with reduce: ranges have it, and you'll lean on it for quick sums and products.

challenge icon

Challenge

Easy

Read two integers (two lines): n and target. Treat the closed range 1...n as your data set.

Print three lines:

  1. true when target is in the range, otherwise false
  2. The product of every value in the range (n!: factorial). Use reduce.
  3. The values in the range that are multiples of 3, joined with , (or an empty line when none qualify). Use filter.

For input 5 / 3, the output is:

true
120
3

Cheat sheet

Ranges conform to Collection and support common collection methods:

let r = 1...10
r.contains(5)   // true
r.count         // 10
r.first!        // 1
r.last!         // 10

filter on a range returns an array:

let evens = (1...10).filter { $0 % 2 == 0 }
// [2, 4, 6, 8, 10]

reduce works directly on ranges:

let product = (1...5).reduce(1) { $0 * $1 }  // 120
let sum = (1...5).reduce(0, +)               // 15

Try it yourself

let n = Int(readLine()!)!
let target = Int(readLine()!)!
let r = 1...n

// TODO: contains(target), product via reduce, multiples of 3 via filter
quiz iconTest yourself

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

All lessons in Logic & Flow