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 10Most 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
EasyRead two integers (two lines): n and target. Treat the closed range 1...n as your data set.
Print three lines:
truewhentargetis in the range, otherwisefalse- The product of every value in the range (
n!: factorial). Usereduce. - The values in the range that are multiples of
3, joined with,(or an empty line when none qualify). Usefilter.
For input 5 / 3, the output is:
true
120
3Cheat 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! // 10filter 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, +) // 15Try 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check