Menu
CoddyTech

Numbers and Conversion

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

C# and Swift both distinguish integer division from floating-point division. Swift does not silently convert an Int operand to Double when you combine numeric types. Convert deliberately before dividing, as shown by the mean of two measurements. In C#, casting one operand to double causes numeric promotion of the other operand. Swift requires both operands to match. Converting a floating value to an integer truncates toward zero when the value is representable; this is not rounding to the nearest integer. Keep these conversions separate from formatting, which determines how a number is displayed.

C#

Complete program file: Program.cs.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int total = 5;
        Console.WriteLine((double)total / 2);
        Console.WriteLine((int)(-2.7));
    }
}

Swift

Complete program file: main.swift.

let total = 5
print(Double(total) / 2.0)
print(Int(-2.7))
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 C# Developers

Practice on your own: Swift playground