Closed vs Half-Open
Part of the Logic & Flow section of Coddy's Swift journey — lesson 7 of 56.
Swift has two range operators that look almost identical but mean different things.
a...b is the closed range. It includes b:
for i in 1...3 { print(i) }
// 1
// 2
// 3a..<b is the half-open range. It stops before b:
for i in 1..<3 { print(i) }
// 1
// 2Half-open is the natural fit when you have a count: 0..<arr.count covers every valid index of the array. Use closed when both ends are real values you care about (like a score range or an inclusive grade boundary).
Challenge
EasyRead two integers (two lines): a and b, with a <= b. Print three lines:
- The values in the closed range
a...b, joined with,on one line - The values in the half-open range
a..<b, joined with,(or an empty line when the range is empty) - The sum of every value in the closed range
For input 1 then 5, the output is:
1,2,3,4,5
1,2,3,4
15Cheat sheet
Range operators in Swift:
a...b— closed range, includes bothaandba..<b— half-open range, includesabut stops beforeb
for i in 1...3 { print(i) } // 1, 2, 3
for i in 1..<3 { print(i) } // 1, 2Use 0..<arr.count to cover every valid array index. Use closed ranges when both endpoints are meaningful values.
Try it yourself
let a = Int(readLine()!)!
let b = Int(readLine()!)!
// TODO: print closed range joined, half-open range joined, sum of closed range
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