Understanding Arithmetic Operators
Introduction to Arithmetic Operators in Swift
Arithmetic operators are essential tools in Swift, allowing
developers to perform fundamental mathematical operations on numeric
data types such as integers and floating-point numbers. These
operators are crucial for computations in programming, providing a
simple and efficient way to manipulate numbers.
Swift ensures safety by preventing arithmetic overflow by default.
However, if you require overflow behavior, Swift provides overflow
operators.
List of Arithmetic Operators in Swift
Operator | Name | Example |
---|---|---|
+ | Addition | 20 + 30 = 50 |
- | Subtraction | 30 - 4 = 26 |
* | Multiplication | 3 * 4 = 12 |
/ | Division | 12 / 6 = 2 |
% | Remainder (Modulus) | 12 % 2 = 0 |
Addition Operator (+) in Swift
The addition operator adds two numerical values or concatenates two strings.
Syntax
var result = value1 + value2
Example: Adding Numeric Values
import
Foundation
let num1
= 45.3
let num2
= 23.5
let result1
= num1
+ num2
print("Sum of \(num1) and
\(num2) is
\(result1) ")
Output
Subtraction Operator (-) in Swift
The subtraction operator calculates the difference between two numbers.
Syntax
var result = value1 - value2
Example
import
Foundation
let num1
= 25.8
let num2
= 12.4
let result1
= num1
- num2
print("Difference: \(result1) ")
Output
Division Operator (/) in Swift
The division operator divides one numeric value by another.
Syntax
var result = value1 / value2
Example
import
Foundation
let num1
= 34.5
let num2
= 3.2
let result1
= num1
/ num2
print("Result: \(result1) ")
Output
Multiplication Operator (*) in Swift
The multiplication operator calculates the product of two numbers.
Syntax
var result = value1 * value2
Example
import
Foundation
let num1
= 34.5
let num2
= 3.2
let result1
= num1
* num2
print("Product: \(result1)")
Output
Remainder Operator (%) in Swift
The remainder operator finds the remainder of a division operation.
Syntax
var result = value1 % value2
Example
import
Foundation
let num1
= -18
let num2
= 7
let result1
= num1
% num2
print("Remainder: \(result1) ")