Swift Assignment Operator

In Swift, Assignment Operator is used to assign a value to a variable.

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

Syntax

The syntax of Assignment Operator is

</>
Copy
x = value

where

Operand / SymbolDescription
xLeft operand. A variable.
=Symbol for 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 assigns the given value to variable x.

Examples

1. Assign integer value to x

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

main.swift

</>
Copy
var x: Int
x = 25
print("x is \(x)")

Output

x is 25

2. Assign string value to x

In the following program, we shall assign a string value of “Hello World” to variable x using Assignment Operator.

main.swift

</>
Copy
var x: String
x = "Hello World"
print("x is \"\(x)\"")

Output

x is "Hello World"

3. Assign expression to x

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

main.swift

</>
Copy
var x: Int
var y = 7
x = (2 + y) * 4
print("x is \(x)")

Output

x is 36

Summary

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