Numbers and Conversion
Lesson 3 of 48 in Coddy's Swift for C++ Developers course.
C++ usual arithmetic conversions can promote an integer operand when combined with double, while Swift requires converting already typed Int values explicitly. Cast before division when a fractional result is needed; casting an integer quotient afterwards cannot restore lost information. Both shown floating-to-integer conversions truncate toward zero for representable values. C++ signed integer overflow is undefined behavior and unsigned arithmetic wraps; Swift ordinary overflowing integer arithmetic traps, with explicit overflow operators for wrapping. A cast is not a bounds-validation policy. Keep representation, domain limits and textual formatting separate when translating numeric operations.
C++
Complete program file: main.cpp.
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
int main() {
int total = 5;
std::cout << static_cast<double>(total) / 2 << '\n';
std::cout << static_cast<int>(-2.7) << '\n';
}
Swift
Complete program file: main.swift.
let total = 5
print(Double(total) / 2.0)
print(Int(-2.7))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 C++ 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