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.
The syntax of Modulus Assignment Operator is
x %= value
|Operand / Symbol||Description|
|x||Left operand. A variable.|
|%=||Symbol for Modulus Assignment Operator.|
|value||Right operand. A value, an expression that evaluates to a value, a variable that holds a value, or a function call that returns a value.|
x %= value computes x % value and assigns this computed value to variable x.
Therefore the expression
x %= value is same as
x = x % value.
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.
var x = 110 x %= 25 print("x is \(x)")
x is 10
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.
var x: Float = 3.14 var y: Float = 1.2 x /= y print("x is \(x)")
In this Swift Operators tutorial, we learned about Modulus Assignment Operator, its syntax, and usage, with examples.