Menu
CoddyTech

Numbers and Conversion

Lesson 3 of 48 in Coddy's Swift for Python Developers course.

Python integers grow to hold large results, subject to memory limits. Swift Int has a fixed width, 64 bits on this course runtime. Ordinary overflowing arithmetic traps; it does not silently become a larger integer. Keep calculations within the stated input bounds.

Python // rounds a quotient down. Swift division between integers truncates toward zero, so negative operands reveal a difference. Python / produces a floating-point result, while Swift needs a floating-point operand. Convert explicitly with Double(...). Converting an in-range floating-point number to Int also truncates toward zero. Swift remainder uses %; do not assume Python remainder signs for negative inputs.

Below, a negative temperature adjustment demonstrates integer division and explicit conversion. The exercise uses nonnegative minutes, so division and remainder can separate its units without the negative rounding distinction.

Complete Python comparison program:

print(-7 // 2)
print(-7 / 2)
print(10 ** 30 > 2 ** 63)

Complete Swift comparison program, compiled from these files:

main.swift

print(-7 / 2)
print(Double(-7) / 2)
print(Int.max > 0)
challenge icon

Challenge

Easy

Implement clockParts(_ minutes: Int) -> String. Input is total minutes, 0 through 10000. Return whole hours, a colon, then remaining minutes, without zero padding.

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 clockParts(181) == "3:1" && clockParts(60) == "1:0"
}
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 Python Developers

Practice on your own: Swift playground