Menu
CoddyTech

For Loops and Ranges

Lesson 13 of 48 in Coddy's Swift for Kotlin Developers course.

Kotlin uses inclusive ranges, until, and downTo to describe iteration. Swift has closed ranges with three dots, half-open ranges with two dots and a less-than sign, and stride for custom steps. A half-open range excludes its upper bound and works naturally with collection counts. A descending numeric traversal should use stride with a negative step rather than constructing a reversed closed range whose lower bound exceeds its upper bound. The stride variant ending with to excludes the endpoint; through includes it if the stepping sequence reaches it. Both languages expose the loop variable as a fresh binding for each iteration.

Kotlin

fun main() {
    val parts = mutableListOf<Int>()
    for (n in 6 downTo 0 step 2) parts.add(n)
    println(parts.joinToString(" "))
}

Swift

var parts: [Int] = []
for n in stride(from: 6, through: 0, by: -2) { parts.append(n) }
print(parts.map(String.init).joined(separator: " "))
challenge icon

Challenge

Easy

Implement multiples(upTo:of:): count multiples of the divisor in the inclusive range 0 through limit, including zero. Input is limit 0 through 1000 and divisor 1 through 100. Output the count.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
return multiples(upTo: 14, of: 4) == 4 && multiples(upTo: 0, of: 2) == 1 && multiples(upTo: 8, of: 4) == 3
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

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

All lessons in Swift for Kotlin Developers

Practice on your own: Swift playground