A Swift literal is a direct value of a variable or a constant. It may be a number, character or string. Literals are used to initialize or assign value to variables or constants.
Different types of literals are:
- Binary Literals
- Octal Literals
- Hexadecimal Literals
- Decimal Literals
In Swift, there are several types of literals:
- Integer literals: These represent whole numbers without a fractional component. Examples include
42
,-17
, and0
. - Floating-point literals: These represent numbers with a fractional component. Examples include
3.14
,-0.5
, and1.0
. - Boolean literals: These represent true or false values. In Swift, the Boolean literals are
true
andfalse
. - String literals: These represent sequences of characters enclosed in double quotes (
"
). Examples include"Hello, world!"
,"Swift"
, and"123"
. - Character literals: These represent a single character enclosed in single quotes (
'
). Examples include'a'
,'5'
, and'$'
. - Nil literal: This represents the absence of a value. In Swift, the nil literal is
nil
, and it is used with optional types to indicate that a variable or constant doesn’t currently have a value. - Array literals: These represent ordered collections of elements enclosed in square brackets (
[]
). Example:[1, 2, 3]
. - Dictionary literals: These represent unordered collections of key-value pairs enclosed in square brackets (
[]
). Each key-value pair is written askey: value
. Example:["name": "John", "age": 30]
. - Tuple literals: These represent fixed-size collections of values of different types. Example:
(1, "apple", true)
.
These are the main types of literals in Swift.