Numbers and Conversion
Lesson 3 of 48 in Coddy's Swift for Go Developers course.
Go and Swift require explicit conversion when combining variables of different numeric types. An untyped Go constant can adapt to context, while an already typed int needs float64 conversion here. Swift uses Double(celsius) for the corresponding operation.
Both languages truncate signed integer division toward zero, so a floating operand must be introduced before division to preserve a fraction. Swift ordinary integer overflow traps. Go integer overflow follows its defined integer representation behavior rather than growing to arbitrary precision. Choose ranges from the task contract.
Go: complete program
main.go
package main
import (
"fmt"
)
func main() {
celsius := 10
fahrenheit := float64(celsius)*1.8 + 32
fmt.Printf("%.1f\n", fahrenheit)
}
Swift: complete program
main.swift
import Foundation
let celsius = 10
let fahrenheit = Double(celsius) * 1.8 + 32
print(fahrenheit)Converting an integer quotient afterwards cannot recover discarded information. Formatting controls presentation, not the precision of the computation that already occurred.
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 Go 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