Numbers and Conversion
Lesson 3 of 48 in Coddy's Swift for JavaScript Developers course.
JavaScript Number uses binary floating-point even when a value looks integral. Division can return a fraction, and Math.trunc removes its fractional part toward zero. Integers beyond the safe-integer range can round, which makes the last comparison true. BigInt provides a separate integer representation and cannot be mixed with Number arithmetic implicitly.
Swift distinguishes Int from Double and requires explicit conversion of typed operands for fractional division. Its bounded Int preserves the displayed large integer increment on this 64-bit runtime, but ordinary arithmetic still traps on overflow. Choose representation and bounds from the contract rather than assuming either Number or Int can represent every integer exactly.
JavaScript
Complete JavaScript console program:
main.js
const paint = 11;
console.log(paint / 4);
console.log(Math.trunc(paint / 4));
console.log(9007199254740992 + 1 === 9007199254740992);
Swift
Complete program; compile the listed files together:
main.swift
import Foundation
let paint = 11
print(Double(paint) / 4.0)
print(paint / 4)
print(9007199254740992 + 1 == 9007199254740992)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 JavaScript 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