Swift provides a robust set of tools for working with numbers and performing mathematical operations. From basic arithmetic to complex calculations, Swift's number and math capabilities are both powerful and easy to use.
Swift supports standard arithmetic operations for all numeric types:
Here's a simple example demonstrating these operations:
let a = 10
let b = 3
let sum = a + b // 13
let difference = a - b // 7
let product = a * b // 30
let quotient = a / b // 3
let remainder = a % b // 1
Swift also provides compound assignment operators that combine an operation with assignment:
var x = 5
x += 3 // x is now 8
x -= 2 // x is now 6
x *= 4 // x is now 24
x /= 3 // x is now 8
x %= 5 // x is now 3
Comparing numbers is a common operation in programming. Swift offers these comparison operators:
These operators return a Boolean value (true
or false
):
let a = 5
let b = 10
print(a == b) // false
print(a != b) // true
print(a < b) // true
print(a > b) // false
print(a <= 5) // true
print(b >= 10) // true
For more complex mathematical operations, Swift provides the Foundation
framework, which includes many useful functions:
import Foundation
let number = 16.0
let squareRoot = sqrt(number) // 4.0
let power = pow(number, 2) // 256.0
let sine = sin(number) // -0.2879033
let cosine = cos(number) // -0.9577764
let naturalLog = log(number) // 2.772589
let roundedDown = floor(3.7) // 3.0
let roundedUp = ceil(3.2) // 4.0
let rounded = round(3.5) // 4.0
Swift supports various numeric types, including integers (Int
) and floating-point numbers (Double
and Float
). It's important to be aware of type conversions when performing operations:
let integerValue: Int = 42
let doubleValue: Double = 42.5
// Type conversion is required
let sum = Double(integerValue) + doubleValue
For more information on Swift's data types, check out the guide on Swift Data Types.
Swift provides built-in functionality for generating random numbers:
let randomInt = Int.random(in: 1...100)
let randomDouble = Double.random(in: 0...1)
Decimal
for financial calculations to avoid floating-point precision issues.Understanding Swift's number and math operations is crucial for developing efficient and accurate applications. These operations form the foundation for more complex algorithms and data processing tasks in Swift programming.
To learn more about how these operations fit into the larger context of Swift programming, explore our guide on Swift Operators.