Swift Multiplication Assignment Operator
In Swift, Multiplication Assignment Operator is used to compute the product of given value in right operand with the value in left operand, and assign the result back to the variable given as left operand.
In this tutorial, we will learn about Multiplication Assignment Operator in Swift language, its syntax, and how to use this operator in programs, with examples.
Syntax
The syntax of Multiplication Assignment Operator is
x *= value
where
Operand / Symbol | Description |
---|---|
x | Left operand. A variable. |
*= | Symbol for Multiplication 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. |
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. Multiplication Assignment of integer value to x
In the following program, we shall multiply and assign an integer value of 25 to variable x using Multiplication Assignment Operator.
main.swift
var x = 7
x *= 10
print("x is \(x)")
Output
x is 70
Explanation
x *= 10
x = x * 10
= 7 * 10
= 70
2. Multiplication Assignment of an expression to x
In the following program, we shall multiply and assign the value of an expression to variable x using Multiplication Assignment Operator.
main.swift
var x = 40
var y = 5
x *= (2 + y) * 4
print("x is \(x)")
Output
x is 1120
Explanation
x *= (2 + y) * 4
x = x * (2 + y) * 4
= 40 * (2 + 5) * 4
= 40 * 28
= 1120
3. Multiplication Assignment with strings
We cannot use Multiplication assignment operator with string values.
main.swift
var x = "Hello "
x *= "Ram"
print("x is \"\(x)\"")
Output
Summary
In this Swift Operators tutorial, we learned about Multiplication Assignment Operator, its syntax, and usage, with examples.