Swift Addition Assignment Operator

In Swift, Addition Assignment Operator is used to compute the sum 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 Addition Assignment Operator in Swift language, its syntax, and how to use this operator in programs, with examples.

Syntax

The syntax of Addition Assignment Operator is

x += value

where

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

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

main.swift

var x = 7
x += 25
print("x is \(x)")

Output

x is 32

Explanation

x += 25

x = x + 25
  = 7 + 25
  = 32

2. Addition Assignment of string value to x

In the following program, we shall addition assign a string value of “Ram” to the value in variable x using Addition Assignment Operator. Addition / Addition Assignment operator concatenates the strings.

main.swift

var x = "Hello "
x += "Ram"
print("x is \"\(x)\"")

Output

x is "Hello Ram"

Explanation

x += "Ram"

x = x + "Ram"
  = "Hello " + "Ram"
  = "Hello Ram"

3. Addition Assign expression to x

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

main.swift

var x = 7
var y = 5
x += (2 + y) * 4
print("x is \(x)")

Output

x is 35

Explanation

x += (2 + y) * 4

x = x + (2 + y) * 4
  = 7 + (2 + 5) * 4
  = 35

Summary

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