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.33333 33
There are different types of Swift literals. They are discussed below:
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)
S
My name is Sam
Integer literals are divided into the following:
0b
. It represents binary values.0x
. It is used to represent hexadecimal values.0o
. It is used to represent octal values.Some examples are shown below:
let binaryInteger = 0b10001 print(binaryInteger) let decimalInteger = 17 print(decimalInteger) let octalInteger = 0o21 print(octalInteger) let hexadecimalInteger = 0x11 print(hexadecimalInteger)
17
17
17
17
Floating point literals can either be represented in decimal form or hexadecimal form.
0x
prefix, an optional hexadecimal fraction, and a hexadecimal exponent.An example is shown below:
let sampleDecimalFloat = 3.14e2 print(sampleDecimalFloat) let sampleHexadecimalFloat = 0xFp10 print(sampleHexadecimalFloat)
314.0
15360.0
There are two types of boolean literals. They are:
An example is shown below:
let sample1: Bool = true print(sample1) let sample2: Bool = false print(sample2)
true
false
RELATED TAGS
CONTRIBUTOR
View all Courses