Menu
CoddyTech

Numbers and Conversion

Lesson 3 of 48 in Coddy's Swift for Java Developers course.

Java can widen an int to a double implicitly. Swift does not implicitly convert an Int operand to Double: construct Double(value) before combining it with a floating-point operand. Keep unit conversions explicit so the result type is apparent.

The temperature conversion uses a floating-point scale. Swift integer literals adapt to context, but an already typed integer variable does not. Both languages truncate integer division toward zero; choosing a floating-point operand before dividing preserves a fractional result. Swift ordinary integer arithmetic traps on overflow; Java int arithmetic wraps.

Java: complete program

Main.java

import java.util.*;
import java.util.function.*;
public class Main {

  public static void main(String[] args) throws Exception {
    int celsius = 10;
    double fahrenheit = celsius * 1.8 + 32;
    System.out.println(fahrenheit);
  }
}

Swift: complete program

main.swift

import Foundation
let celsius = 10
let fahrenheit = Double(celsius) * 1.8 + 32
print(fahrenheit)

A cast after integer division cannot recover the discarded fraction. Convert an operand before the division when a fractional result is needed.

challenge icon

Challenge

Easy

Implement 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") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Java Developers

Practice on your own: Swift playground