Arithmetic Operators in Swift
Arithmetic Operators are used to perform basic mathematical arithmetic operators like addition, subtraction, multiplication, etc.
The following table lists out all the arithmetic operators in Swift.
| Operator Symbol | Name | Example | Description |
|---|---|---|---|
+ | Addition | x + y | Returns the sum of values in x and y. |
- | Subtraction | x - y | Returns the subtraction y from x. |
* | Multiplication | x * y | Returns the product of values in x and y. |
/ | Division | x / y | Returns the quotient in the division of x by y. |
% | Modulus | x % y | Returns the remainder in the division of x by y. |
Arithmetic Operators
1. Addition
Addition operator takes two numeric values as inputs: x and y, and returns the result of their sum.
main.swift
var x = 5
var y = 2
var result = x + y
print("\(x) + \(y) is \(result)")
Output
5 + 2 is 7
2. Subtraction
Subtraction operator takes two numeric values as inputs: x and y, and returns the difference of right operand y from the left operand x.
main.swift
var x = 5
var y = 2
var result = x - y
print("\(x) - \(y) is \(result)")
Output
5 - 2 is 3
3. Multiplication
Multiplication operator takes two numeric values as inputs, and returns the result of their product.
main.swift
var x = 5
var y = 2
var result = x * y
print("\(x) * \(y) is \(result)")
Output
5 * 2 is 10
4. Division
Division operator takes two numeric values as inputs: x and y, and returns the quotient of the division of the left operand x by the right operand y.
If x and y are integers, then the division operator performs integer division, and returns an integer quotient value.
main.swift
var x = 5
var y = 2
var result = x / y
print("\(x) / \(y) is \(result)")
Output
5 / 2 is 2
If x and y are floating point numbers, then the division operator performs floating point division, and returns a floating point quotient value.
main.swift
var x: Float = 5.0
var y: Float = 2
var result = x / y
print("\(x) / \(y) is \(result)")
Output
5.0 / 2.0 is 2.5
5. Modulo
Division operator takes two numeric values as inputs: x and y, and returns the remainder of the division of the left operand x by the right operand y.
Modulo operator can be used with integer values only.
main.swift
var x = 5
var y = 2
var result = x % y
print("\(x) % \(y) is \(result)")
Output
5 % 2 is 1
Conclusion
In this Swift Tutorial, we learned about Arithmetic Operators in Swift language, different Arithmetic operators: Addition, Subtraction, Multiplication, Division, and Modulo, with examples.
