Swift provides two primary categories of numbers: integers and floating-point numbers.
0, 1, -1, 42, and -273.0.0, 3.14, and -1.36969e-10.You can insert underscores into numeric literals to improve readability: 1_000_000 is identical to 1000000.
Floating-point literals can be written in decimal or exponential notation.
In most cases, you use Int for integers and Double for floating-point numbers:
let speed: Int = 42 // Explicit Int
let pi: Double = 3.14 // Explicit Double
let giga: Double = 1_000_000_000 // Double with readability underscores
let plancksConstant: Double = 6.62607015e-34 // Double in scientific notation
Swift provides standard arithmetic operators for numeric calculations:
| Operator | Description | Example |
|---|---|---|
+ |
Addition |
4 + 6 evaluates to 10
|
- |
Subtraction |
15 - 10 evaluates to 5
|
* |
Multiplication |
2 * 3 evaluates to 6
|
Swift is type-safe and does not allow mixing different numeric types in arithmetic operations.
You cannot directly add or multiply an Int and a Double; you must convert one type to match the other first.
The / operator performs division.
When both operands are integers, integer division truncates any fractional remainder:
5.0 / 2.0 // 2.5 (Double division)
5 / 2 // 2 (integer division truncates the remainder)
Dividing a non-zero floating-point number by zero results in inf or -inf.
Dividing 0.0 by 0.0 produces nan (Not a Number).
In contrast, dividing an integer by zero causes a compile-time or runtime error:
print(5.0 / 0.0) // Prints inf
print(-5.0 / 0.0) // Prints -inf
print(0.0 / 0.0) // Prints nan
// The following line will not compile:
// print(5 / 0) // Error: Division by zero
The remainder operator (%) calculates the remainder left over after dividing two integers:
5 % 2 // 1
-5 % 2 // -1
// Dividing by zero produces an error:
// 5 % 0 // Error: Division by zero
In Swift, % is a true remainder operator rather than a modulo operator.
The result always takes the sign of the first operand (the dividend), regardless of the sign of the second operand:
5 % -2 // 1
-5 % 2 // -1
You can round a floating-point number using the rounded() method.
By default, rounded() rounds to the nearest integer.
You can also supply a specific rounding rule, such as .up or .down:
let x = 3.14
let y = x.rounded() // 3.0
let w = x.rounded(.down) // 3.0
let z = x.rounded(.up) // 4.0
When you declare a numeric constant or variable without a type annotation, Swift infers its type:
Int.Double.let x = 42 // Inferred as Int
let y = 42.0 // Inferred as Double
let z: Double = 42 // Explicitly typed as Double
To perform operations between values of different types, convert one value using type initializers like Double(_:) or Int(_:):
let integerCount = 42
let floatingCount = Double(integerCount)
print(floatingCount) // Prints 42.0
let pi = 3.14
let integerPi = Int(pi)
print(integerPi) // Prints 3 (fractional part is truncated)
In this exercise you will be writing code to help a freelancer communicate with their clients about the prices of certain projects. You will write a few utility functions to quickly calculate the costs for the clients.
A client contacts the freelancer to enquire about their rates. The freelancer explains that they work 8 hours a day. However, the freelancer knows only their hourly rates for the project. Help them estimate a day rate given an hourly rate.
Implement the function dailyRateFrom(hourlyRate:), that takes the argument hourlyRate which holds the freelancers hourly rate.
The function should return the daily rate based on the hourly rate.
dailyRateFrom(hourlyRate: 60)
// Returns 480.0
The returned daily rate should be a Double.
Sometimes, a client is interested in hiring the freelancer for a longer period of time. The freelancer is willing to give a discount to the client, but only if the client hires them for at least a month. There is in total 22 workdays. Help the freelancer calculate their monthly rate given their hourly rate and the percentage discounted to the flat rate they are willing to give, rounded to the nearest whole number.
Implement the function monthlyRateFrom(hourlyRate:withDiscount:), that takes the arguments hourlyRate which holds the freelancers hourly rate, and withDiscount which holds the discount the freelancer is willing to give to the client.
The function should return the monthly rate rounded to the nearest whole number.
monthlyRateFrom(hourlyRate: 77, withDiscount: 10.5)
// Returns 12129
Another day, a project manager offers the freelancer to work on a project with a fixed budget. Given the fixed budget and the freelancer's hourly rate, help them calculate the number of days they would work until the budget is exhausted. Take into account that in this scenario the freelancer is always willing to give the discount regardless of the number of days hired. The result must be rounded down to the nearest whole number.
Implement the function workdaysIn(budget:hourlyRate:withDiscount:), that takes the arguments:
budget which holds the budget for the project.hourlyRate which holds the freelancers hourly rate.withDiscount which holds the discount the freelancer is willing to give to the client.The function should return the number of workdays the freelancer will work on the project rounded down.
workdaysIn(budget: 20000, hourlyRate: 80, withDiscount: 11.0)
// Returns 35.0
Sign up to Exercism to learn and master Swift with 35 concepts116 exercises, and real human mentoring, all for free.