Numbers and Conversion
Lesson 3 of 48 in Coddy's Swift for R Developers course.
R numeric literals normally create doubles, while the L suffix requests integer storage. Doubles lose exact unit increments beyond their precision range; ordinary integer vectors have a much smaller fixed-width range. R %/% floors a quotient, and %% follows that floor division convention rather than Swift's truncation rule.
Swift Int and Double are distinct types. Integer division truncates toward zero, and Double conversion before division preserves a fractional result. Int is 64-bit on this runtime and ordinary overflow traps. Converting an already truncated integer quotient afterwards cannot restore the lost fraction.
The negative quotient is -4 in R and -3 in Swift. Both fractional divisions produce -3.5, and the R precision comparison illustrates why a numeric-looking value is not automatically an exact integer. Keep the task's bounded arithmetic distinct from general vector calculations.
Complete R comparison program:
cat(-7 %/% 2, "\n", sep = "")
cat(-7 / 2, "\n", sep = "")
cat(tolower(as.character(2^53 + 1 == 2^53)), "\n", sep = "")
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 R 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