Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Arithmetic Operators in Swift
Written by Team Kodeco

Swift provides a set of basic arithmetic operators that can be used to perform mathematical operations such as addition, subtraction, multiplication and division. The basic arithmetic operators in Swift are:

  • + for addition.
  • - for subtraction.
  • * for multiplication.
  • / for division.
  • % for modulo.

Here’s an example of using arithmetic operators to perform mathematical operations:

let a = 5
let b = 2

let sum = a + b // 7
let difference = a - b // 3
let product = a * b // 10
let quotient = a / b // 2
let remainder = a % b // 1

print("sum: \(sum)")
print("difference: \(difference)")
print("product: \(product)")
print("quotient: \(quotient)")
print("remainder: \(remainder)")

// Output: sum: 7
//         difference: 3
//         product: 10
//         quotient: 2
//         remainder: 1

In this example, the variables a and b are set to 5 and 2 respectively. The basic arithmetic operators are used to perform addition, subtraction, multiplication and division operations. The result of each operation is stored in a separate variable and printed.

© 2024 Kodeco Inc.