Swift Modulus Assignment Operator

In Swift, Modulus Assignment Operator is used to compute the division of given value in left operand by the value in right operand, and assign the remainder in this division operation to the variable given as left operand.

In this tutorial, we will learn about Modulus Assignment Operator in Swift language, its syntax, and how to use this operator in programs, with examples.

Syntax

The syntax of Modulus Assignment Operator is

</>
Copy
x %= value

where

Operand / SymbolDescription
xLeft operand. A variable.
%=Symbol for Modulus Assignment Operator.
valueRight operand. A value, an expression that evaluates to a value, a variable that holds a value, or a function call that returns a value.

The expression x %= value computes x % value and assigns this computed value to variable x.

Therefore the expression x %= value is same as x = x % value.

Examples

1. Modulus Assignment of integer value to x

In the following program, we shall modulus assign an integer value of 25 to variable x using Modulus Assignment Operator.

main.swift

</>
Copy
var x = 110
x %= 25
print("x is \(x)")

Output

x is 10

Explanation

x %= 25

x = x % 25
  = 110 % 25
  = 10 (integer remainder)

2. Modulus Assign with float values

Modulus assignment cannot be done with floating point values.

main.swift

</>
Copy
var x: Float = 3.14
var y: Float = 1.2
x /= y
print("x is \(x)")

Output

modulus assignment is unavailable: for floating point numbers

Summary

In this Swift Operators tutorial, we learned about Modulus Assignment Operator, its syntax, and usage, with examples.