Swift Subtraction Assignment Operator

In Swift, Subtraction Assignment Operator is used to compute the difference of given value in right operand from the value in left operand, and assign the result back to the variable given as left operand.

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

Syntax

The syntax of Subtraction Assignment Operator is

</>
Copy
x -= value

where

Operand / SymbolDescription
xLeft operand. A variable.
-=Symbol for Subtraction 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. Subtraction Assignment of integer value to x

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

main.swift

</>
Copy
var x = 70
x -= 25
print("x is \(x)")

Output

x is 45

Explanation

x -= 25

x = x - 25
  = 70 - 25
  = 45

2. Subtraction Assignment of an expression to x

In the following program, we shall subtract and assign the value of an expression to variable x using Subtraction Assignment Operator.

main.swift

</>
Copy
var x = 40
var y = 5
x -= (2 + y) * 4
print("x is \(x)")

Output

x is 12

Explanation

x -= (2 + y) * 4

x = x - (2 + y) * 4
  = 40 - (2 + 5) * 4
  = 40 - 28
  = 12

3. Subtract Assignment with strings

We cannot use Subtraction assignment operator with string values.

main.swift

</>
Copy
var x = "Hello "
x -= "Ram"
print("x is \"\(x)\"")

Output

Binary operator -= cannot be applied to two string operands

Summary

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