Swift Introduction | Values, Variables, and Operations | Literals

Values and variables are fundamental programming concepts. This article begins with values written directly in source code.

A value written directly in source code is called a literal. Literal syntax is similar in many programming languages.

Numeric Literals

Write ordinary numbers directly, such as 123 or 0.45. Swift also supports several other forms.

Separating Digits with Underscores

Long numbers can be difficult to read. Swift lets you separate digits with underscores (_) instead of commas. You can also add leading zeros to align digits.

Example: 0012_3456_7890 (the same as 1234567890)

Binary, Octal, and Hexadecimal Numbers

In addition to decimal numbers, you can write binary, octal, and hexadecimal values.

Base Description Example
Binary Add 0b at the beginning. 0b11011
Octal Add 0o at the beginning. The second character is the letter o. 0o7623
Hexadecimal Add 0x at the beginning. Use digits 0-9 and letters A-F. 0x5fa3

Text Literals

Write text between double quotation marks (").

Example: "Hello", "Hello there"

Escape Sequences

Some characters cannot be written directly in a text literal. Use a backslash (\) to write characters such as quotation marks and line breaks.

Sequence Description
\" Double quotation mark (")
\\ Backslash (\)
\t Horizontal tab
\r Carriage return
\n Line feed
\0 Null character
Example: "This is a \"double\\quote\" symbol\n"

Including Variables

Include a variable in a literal with \(variable).

Example: "Display \(str) here"

Boolean Literals

Boolean values represent one of two states. Swift provides the literals true and false.