Swift Literals

Understanding different types of literal values in Swift

💎 What are Literals?

Literals in Swift are fixed values written directly in your code. They represent specific data like numbers, text, or boolean values that don't change during compilation.


// Examples of different literals
let number = 42        // Integer literal
let text = "Hello"     // String literal
let flag = true        // Boolean literal
                                    

Output:

Number: 42

Text: Hello

Flag: true

Types of Literals

🔢

Integer Literals

Whole numbers without decimals

let age = 25
let year = 2024
📊

Floating-Point

Numbers with decimal points

let price = 19.99
let pi = 3.14159
📝

String Literals

Text enclosed in quotes

let name = "John"
let message = "Hello!"

Boolean Literals

True or false values

let isActive = true
let isComplete = false

🔹 Integer Literals

Integer literals represent whole numbers in different formats:

// Decimal (base 10) - most common
let decimal = 42
let largeNumber = 1000000

// Binary (base 2) - prefix with 0b
let binary = 0b1010      // equals 10 in decimal
let binaryLarge = 0b11111111  // equals 255 in decimal

// Octal (base 8) - prefix with 0o
let octal = 0o52         // equals 42 in decimal
let octalLarge = 0o377   // equals 255 in decimal

// Hexadecimal (base 16) - prefix with 0x
let hex = 0x2A           // equals 42 in decimal
let hexLarge = 0xFF      // equals 255 in decimal

// Using underscores for readability
let million = 1_000_000
let creditCard = 1234_5678_9012_3456

print("Decimal: \(decimal)")
print("Binary 0b1010: \(binary)")
print("Octal 0o52: \(octal)")
print("Hex 0x2A: \(hex)")
print("Million: \(million)")
print("Credit Card: \(creditCard)")

Output:

Decimal: 42

Binary 0b1010: 10

Octal 0o52: 42

Hex 0x2A: 42

Million: 1000000

Credit Card: 1234567890123456

🔹 Floating-Point Literals

Floating-point literals represent decimal numbers:

// Standard decimal notation
let price = 19.99
let temperature = -5.5
let zero = 0.0

// Scientific notation (e or E)
let scientific1 = 1.25e2     // 1.25 × 10² = 125.0
let scientific2 = 1.25e-2    // 1.25 × 10⁻² = 0.0125
let avogadro = 6.022E23      // Avogadro's number

// Hexadecimal floating-point (0x with p for exponent)
let hexFloat = 0xC.3p0       // 12.1875 in decimal

// Using underscores for readability
let bigDecimal = 123_456.789_012
let percentage = 0.123_456

print("Price: $\(price)")
print("Temperature: \(temperature)°C")
print("Scientific 1.25e2: \(scientific1)")
print("Scientific 1.25e-2: \(scientific2)")
print("Avogadro: \(avogadro)")
print("Hex float: \(hexFloat)")
print("Big decimal: \(bigDecimal)")
print("Percentage: \(percentage)")

Output:

Price: $19.99

Temperature: -5.5°C

Scientific 1.25e2: 125.0

Scientific 1.25e-2: 0.0125

Avogadro: 6.022e+23

Hex float: 12.1875

Big decimal: 123456.789012

Percentage: 0.123456

🔹 String Literals

String literals represent text data:

// Basic string literals
let greeting = "Hello, World!"
let name = "Alice"
let empty = ""

// Strings with special characters
let quote = "She said, \"Hello there!\""
let path = "C:\\Users\\Documents\\file.txt"
let newline = "First line\nSecond line"
let tab = "Column1\tColumn2"

// Multi-line strings (triple quotes)
let poem = """
    Roses are red,
    Violets are blue,
    Swift is awesome,
    And so are you!
    """

// Raw strings (ignore escape sequences)
let rawString = #"This is a "quote" and \n is not a newline"#

// String interpolation
let age = 25
let introduction = "Hi, I'm \(name) and I'm \(age) years old."

print("Greeting: \(greeting)")
print("Quote: \(quote)")
print("Path: \(path)")
print("With newline:")
print(newline)
print("With tab:")
print(tab)
print("Poem:")
print(poem)
print("Raw string: \(rawString)")
print("Introduction: \(introduction)")

Output:

Greeting: Hello, World!

Quote: She said, "Hello there!"

Path: C:\Users\Documents\file.txt

With newline:

First line

Second line

With tab:

Column1 Column2

Poem:

Roses are red,

Violets are blue,

Swift is awesome,

And so are you!

Raw string: This is a "quote" and \n is not a newline

Introduction: Hi, I'm Alice and I'm 25 years old.

🔹 Boolean and Character Literals

Boolean and character literals for simple data types:

// Boolean literals
let isSwiftFun = true
let isHard = false
let isComplete = true
let hasErrors = false

// Character literals
let firstLetter: Character = "A"
let grade: Character = "B"
let symbol: Character = "★"
let emoji: Character = "😊"
let number: Character = "5"

// Nil literal (for optionals)
var optionalName: String? = nil
var optionalAge: Int? = nil

print("=== Boolean Values ===")
print("Swift is fun: \(isSwiftFun)")
print("Swift is hard: \(isHard)")
print("Project complete: \(isComplete)")
print("Has errors: \(hasErrors)")

print("\n=== Character Values ===")
print("First letter: \(firstLetter)")
print("Grade: \(grade)")
print("Symbol: \(symbol)")
print("Emoji: \(emoji)")
print("Number character: \(number)")

print("\n=== Optional Values ===")
print("Optional name: \(optionalName ?? "No name")")
print("Optional age: \(optionalAge ?? 0)")

// Assign values to optionals
optionalName = "John"
optionalAge = 30

print("\nAfter assignment:")
print("Optional name: \(optionalName ?? "No name")")
print("Optional age: \(optionalAge ?? 0)")

Output:

=== Boolean Values ===

Swift is fun: true

Swift is hard: false

Project complete: true

Has errors: false

=== Character Values ===

First letter: A

Grade: B

Symbol: ★

Emoji: 😊

Number character: 5

=== Optional Values ===

Optional name: No name

Optional age: 0

After assignment:

Optional name: John

Optional age: 30

🔹 Array and Dictionary Literals

Collection literals for arrays and dictionaries:

// Array literals
let numbers = [1, 2, 3, 4, 5]
let fruits = ["Apple", "Banana", "Orange"]
let mixed: [Any] = [1, "Hello", true, 3.14]
let empty: [String] = []

// Dictionary literals
let ages = ["Alice": 25, "Bob": 30, "Charlie": 35]
let settings = [
    "theme": "dark",
    "language": "en",
    "notifications": "enabled"
]
let emptyDict: [String: Int] = [:]

// Nested collections
let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print("=== Arrays ===")
print("Numbers: \(numbers)")
print("Fruits: \(fruits)")
print("Mixed: \(mixed)")
print("Empty array count: \(empty.count)")

print("\n=== Dictionaries ===")
print("Ages: \(ages)")
print("Settings: \(settings)")
print("Empty dict count: \(emptyDict.count)")

print("\n=== Nested Array ===")
print("Matrix: \(matrix)")
print("First row: \(matrix[0])")
print("Center element: \(matrix[1][1])")

// Accessing dictionary values
if let aliceAge = ages["Alice"] {
    print("\nAlice is \(aliceAge) years old")
}

if let theme = settings["theme"] {
    print("Current theme: \(theme)")
}

Output:

=== Arrays ===

Numbers: [1, 2, 3, 4, 5]

Fruits: ["Apple", "Banana", "Orange"]

Mixed: [1, "Hello", true, 3.14]

Empty array count: 0

=== Dictionaries ===

Ages: ["Alice": 25, "Bob": 30, "Charlie": 35]

Settings: ["theme": "dark", "language": "en", "notifications": "enabled"]

Empty dict count: 0

=== Nested Array ===

Matrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

First row: [1, 2, 3]

Center element: 5

Alice is 25 years old

Current theme: dark

🧠 Test Your Knowledge

What is the binary literal 0b1010 equal to in decimal?