Numbers and Conversion
Lesson 3 of 48 in Coddy's Swift for Dart Developers course.
Dart / produces a double even for two integers, while ~/ truncates an integer quotient toward zero. Swift chooses division from operand types: two Int operands produce an integer quotient. Convert operands with Double(...) before dividing when a fractional result is needed. Swift does not implicitly mix a stored Int with a stored Double. Integer literals can be inferred in a floating-point context, which is different from converting an existing variable. These examples scale a negative measurement, so truncation toward zero is visible.
Complete Dart program. Each labelled block is a separate file.
main.dart
void main() {
final measurement = -9;
print(measurement ~/ 2);
print(measurement / 2);
}Complete Swift program. Each labelled block is a separate file.
main.swift
import Foundation
let measurement = -9
print(measurement / 2)
print(Double(measurement) / 2.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 Dart 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