What are literals in Swift?
A sequence of characters representing constant values stored in variables is referred to as a literal. Literals play a significant role in dealing with values within a program.
Examples of Swift literals are shown below:
"Hi, there!"3.3333333
There are different types of Swift literals. They are discussed below:
1. String literals
A string literal is a sequence of characters wrapped with a starting double quote and a closing double quote. Special characters are used in string literals to form a branch of string literals known as an escape sequence.
The difference between a string and a character literal is that a string literal contains a sequence of characters, while a character literal contains a single character. An example is shown below:
var sampleCharacter: Character = "S"print(sampleCharacter)var sampleString: String = "My name is Sam"print(sampleString)
Output
S
My name is Sam
2. Integer literals
Integer literals are divided into the following:
- Binary literals: It starts with the prefix
0b. It represents binary values. - Decimal literals: Every value declared in an integer literal is of type decimal. Hence, it is not preceded by any number or character as in the binary literals above.
- Hexadecimal literals: It starts with the prefix
0x. It is used to represent hexadecimal values. - Octal literals: It starts with the prefix
0o. It is used to represent octal values.
Some examples are shown below:
let binaryInteger = 0b10001print(binaryInteger)let decimalInteger = 17print(decimalInteger)let octalInteger = 0o21print(octalInteger)let hexadecimalInteger = 0x11print(hexadecimalInteger)
Output
17
17
17
17
3. Floating point literals
Floating point literals can either be represented in decimal form or hexadecimal form.
- Decimal floating-point literals: They are made up of a sequence of decimal digits and a decimal fraction or a decimal exponent, or both.
- Hexadecimal floating-point literals: It comprises a
0xprefix, an optional hexadecimal fraction, and a hexadecimal exponent.
An example is shown below:
let sampleDecimalFloat = 3.14e2print(sampleDecimalFloat)let sampleHexadecimalFloat = 0xFp10print(sampleHexadecimalFloat)
Output
314.0
15360.0
4. Boolean literals
There are two types of boolean literals. They are:
- true
- false
An example is shown below:
let sample1: Bool = trueprint(sample1)let sample2: Bool = falseprint(sample2)
Output
true
false