Swift Literals

In Swift, literals are fixed values written directly in your code that represent specific types of data. For example, 42 is an integer literal, and "Hello, World!" is a string literal. Literals are the building blocks for initializing variables or constants.


Types of Literals in Swift

Swift provides various types of literals, which are categorized based on the data they represent:

  • Numeric Literals: Represent numbers (e.g., integers, floating-point numbers).
  • String Literals: Represent text enclosed in double quotes.
  • Boolean Literals: Represent the truth values true or false.
  • Array Literals: Represent collections of values enclosed in square brackets.
  • Dictionary Literals: Represent key-value pairs enclosed in square brackets and separated by colons.
  • Nil Literal: Represents the absence of a value using nil.

1. Numeric Literals

Numeric literals represent numbers and can be written in different forms:

  • Integer Literals: Whole numbers (e.g., 42, -7).
  • Floating-Point Literals: Numbers with a decimal point (e.g., 3.14, -0.01).

Example

</>
Copy
let age = 25 // Integer literal
let pi = 3.14159 // Floating-point literal

2. String Literals

String literals represent text enclosed in double quotes ("").

Example

</>
Copy
let greeting = "Hello, Swift!" // String literal

3. Boolean Literals

Boolean literals represent truth values: true or false.

Example

</>
Copy
let isSwiftFun = true // Boolean literal
let isHard = false // Boolean literal

4. Array Literals

Array literals represent a collection of values, enclosed in square brackets ([]).

Example

</>
Copy
let fruits = ["Apple", "Banana", "Cherry"] // Array literal

5. Dictionary Literals

Dictionary literals represent key-value pairs, enclosed in square brackets with keys and values separated by colons (:).

Example

</>
Copy
let user = ["name": "John", "age": 30] // Dictionary literal

6. Nil Literal

The nil literal represents the absence of a value.

Example

</>
Copy
var optionalValue: Int? = nil // Nil literal

Note: Literals are interpreted by the Swift compiler based on their context. For example, 42 is automatically recognised as an integer unless explicitly specified otherwise.


Conclusion

Literals in Swift provide a straightforward way to represent fixed values directly in your code.