What type of literals does Swift language have?

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:

  1. Integer literals: These represent whole numbers without a fractional component. Examples include 42, -17, and 0.
  2. Floating-point literals: These represent numbers with a fractional component. Examples include 3.14, -0.5, and 1.0.
  3. Boolean literals: These represent true or false values. In Swift, the Boolean literals are true and false.
  4. String literals: These represent sequences of characters enclosed in double quotes ("). Examples include "Hello, world!", "Swift", and "123".
  5. Character literals: These represent a single character enclosed in single quotes ('). Examples include 'a', '5', and '$'.
  6. 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.
  7. Array literals: These represent ordered collections of elements enclosed in square brackets ([]). Example: [1, 2, 3].
  8. Dictionary literals: These represent unordered collections of key-value pairs enclosed in square brackets ([]). Each key-value pair is written as key: value. Example: ["name": "John", "age": 30].
  9. 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.