Numbers and Conversion
Lesson 3 of 48 in Coddy's Swift for PHP Developers course.
PHP distinguishes integers and floating-point numbers. intdiv truncates toward zero, whereas / performs division that can produce a floating-point quotient. Integer width depends on the platform, and the course runtime is 64-bit. Overflowing PHP integer arithmetic can produce a float, so it does not preserve unlimited exact integer results.
Swift Int is 64-bit on this runtime and ordinary overflow traps. Two Int operands use truncating integer division; convert to Double before dividing for a fractional result. Swift requires explicit conversions between existing numeric types instead of relying on PHP scalar coercion rules.
Both examples produce -3 for the integer quotient and -3.5 for the fractional quotient. Converting an already-truncated quotient later cannot restore its fraction. The task uses bounded nonnegative values; choose operations that preserve that exact contract.
Complete PHP comparison program:
<?php
declare(strict_types=1);
echo intdiv(-7, 2), "\n";
echo -7 / 2, "\n";
echo PHP_INT_MAX > 0 ? "true\n" : "false\n";
Complete Swift comparison program, compiled from these files:
main.swift
print(-7 / 2)
print(Double(-7) / 2)
print(Int.max > 0)Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for PHP Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground