Swift Literals and Raw Strings (#"..."#) Explained

Swift literals let you write fixed values directly in code, and raw strings give you more control over how string content is interpreted. This matters whenever you need to include backslashes, quotes, regular expressions, JSON snippets, file paths, or text that would otherwise require a lot of escaping. In this article, you will learn what Swift literals are, how raw strings work, how they compare to normal string literals, and how to use them correctly in real programs.

Quick answer: In Swift, a literal is a fixed value written directly in code, such as a number, Boolean, or string. A raw string uses number signs around the quotes, such as #"Hello"#, and treats backslashes and quotes more literally, which reduces escaping and makes complex strings easier to read.

Difficulty: Beginner

Helpful to know first: You will understand this better if you already know basic Swift syntax, how variables store values, and how normal string literals use quotes and escape sequences.

1. What Is Swift Literals & Raw Strings?

A literal is a value you type directly into Swift source code instead of computing it at runtime. Swift supports several kinds of literals, including numbers, Booleans, characters, arrays, dictionaries, and strings.

Raw strings are a special form of string literal. They are still strings, but Swift changes how escape sequences and interpolation are interpreted.

A common comparison here is normal strings versus raw strings. Both create values of type String, but they differ in how Swift interprets special characters inside them.

2. Why Swift Literals & Raw Strings Matter

Literals are one of the most common things you use in Swift. Every time you assign a direct value to a variable or constant, compare against a fixed value, or print a message, you are probably using literals.

Raw strings matter because normal strings can become hard to read when they contain many backslashes or quote characters. For example, a regular expression pattern or a JSON sample inside a normal string may require several escape characters. That extra escaping increases the chance of mistakes.

Use raw strings when:

You do not need raw strings for every string. If a normal string is short and clear, normal syntax is usually easier to read.

3. Basic Syntax or Core Idea

Normal literals in Swift

Here are a few common literal types written directly in Swift code.

let age = 30                 // Int literal
let price = 19.99           // Double literal
let isReady = true           // Bool literal
let letter: Character = "A"
let name = "Mina"           // String literal

Each line creates a value directly from the source code itself. Swift infers the type in many cases, though explicit types can also be added.

Normal string literals

A normal string uses double quotes. Escape sequences such as \n and interpolation such as \(name) work automatically.

let name = "Mina"
let message = "Hello, \(name)!\nWelcome back."
print(message)

This string includes both interpolation and a newline escape sequence.

Raw string literals

A raw string adds # around the opening and closing quotes. Inside it, Swift stops treating ordinary backslashes as escape markers.

let path = #"C:\Users\Mina\Documents"#
print(path)

Because this is a raw string, the backslashes stay as literal backslashes in the text. You do not need to double-escape them the way you often would in a normal string.

Interpolation inside a raw string

Interpolation still works, but it must match the raw string delimiter. With one #, interpolation becomes \#(value).

let city = "Seoul"
let text = #"Current city: \#(city)"#
print(text)

The output includes the value of city because the interpolation syntax matches the raw string delimiter.

4. Step-by-Step Examples

Example 1: A basic normal string literal

This first example shows standard string behavior with normal escaping and interpolation.

let userName = "Ava"
let greeting = "Hello, \(userName)!"
print(greeting)

This is the normal form you should use for everyday strings when escaping is simple.

Example 2: Including quote characters more easily

Quoted text can get noisy in a normal string because inner quotes must be escaped. Raw strings make this cleaner.

let quote = #"She said, "Swift is readable.""#
print(quote)

The inner quotes are preserved as part of the string without needing \" everywhere.

Example 3: Writing a regular expression pattern

Regular expression patterns often use many backslashes. Raw strings reduce visual clutter.

let pattern = #"^\d{3}-\d{4}$"#
print(pattern)

This pattern is easier to read because the backslashes are written as they appear in the regex itself.

Example 4: Interpolation in a raw string

When you use a raw string and still want Swift to evaluate a value, add the matching # to the interpolation syntax.

let product = "Keyboard"
let price = 79
let label = #"Item: \#(product), Price: $\#(price)"#
print(label)

This keeps the string raw while still allowing selected Swift expressions to be evaluated.

Example 5: Multiline raw string

Raw strings also work with multiline strings. This is useful for embedded text blocks, JSON, or sample output.

let jsonSample = #"""
{
  "name": "Ava",
  "role": "Developer",
  "path": "C:\Users\Ava"
}
"""#

print(jsonSample)

This form is much easier to read than a heavily escaped one-line string.

5. Practical Use Cases

6. Common Mistakes

Mistake 1: Using normal interpolation syntax inside a raw string

Beginners often expect \(value) to work inside a raw string just like it does in a normal string. It does not, because the raw string changes how backslashes are interpreted.

Problem: This code leaves the interpolation as plain text instead of evaluating it, because the interpolation syntax does not match the raw string delimiter.

let name = "Noah"
let message = #"Hello, \(name)!"#
print(message)

Fix: Use \#(value) when the raw string uses one # delimiter.

let name = "Noah"
let message = #"Hello, \#(name)!"#
print(message)

The corrected version works because the interpolation syntax now matches the raw string delimiter.

Mistake 2: Forgetting that raw strings still need matching delimiters

Raw strings must start and end with the same number of # characters. If they do not match, Swift cannot parse the string correctly.

Problem: This code has mismatched delimiters, which causes a compile-time parsing error such as an unterminated string literal.

let title = #"Swift Raw Strings"##

Fix: Make sure the opening and closing sides use the same number of # characters.

let title = #"Swift Raw Strings"#

The corrected version works because Swift can clearly detect where the raw string begins and ends.

Mistake 3: Using a raw string when a normal string is clearer

Raw strings are helpful, but they are not always the best choice. A simple normal string is often easier to understand when escaping is minimal.

Problem: This code adds extra syntax without solving a real readability problem, which can make basic text look more complicated than necessary.

let status = #"Ready"#

Fix: Use a normal string when you do not need literal backslashes, embedded quotes, or raw-string behavior.

let status = "Ready"

The corrected version works because it keeps the code simple while producing the same string value.

Mistake 4: Confusing raw strings with multiline strings

A raw string and a multiline string are related but not identical features. You can use either one independently, or combine them when needed.

Problem: This code uses a normal multiline string and assumes backslashes will be treated literally, but normal escape rules still apply.

let text = """
Path: C:\Users\Ava
Regex: \d+
"""

Fix: Use a multiline raw string if you want multiple lines and raw-string escaping behavior at the same time.

let text = #"""
Path: C:\Users\Ava
Regex: \d+
"""#

The corrected version works because it combines multiline formatting with raw string rules.

7. Best Practices

Use raw strings for readability, not just because they exist

If a normal string is already clear, keep it normal. Use raw strings when they make the content easier to read and maintain.

// Less preferred for a simple value
let mode = #"Dark"#

// Preferred
let mode = "Dark"

This practice keeps everyday code simple and uses raw strings where they provide real benefit.

Match the number of number signs carefully

When a string needs to contain patterns that would conflict with one #, you can use more. Then your interpolation must also match.

let value = "Swift"
let text = ##"This shows # and also interpolates: \##(value)"##
print(text)

This makes delimiter conflicts manageable without giving up interpolation.

Prefer multiline raw strings for large embedded text blocks

Large pieces of text are easier to edit when they keep their natural formatting.

let template = #"""
Dear Customer,

Your order has shipped.
Tracking path: C:\Orders\Current

Thank you.
"""#

This is easier to maintain than building a long string with many manual newline escapes.

8. Limitations and Edge Cases

9. Practical Mini Project

This small program builds a formatted debug report. It uses normal literals for numbers and Booleans, a raw string for a Windows-style path and regex pattern, and interpolation inside a raw string.

let userName = "Ava"
let loginCount = 12
let isAdmin = false

let report = #"""
User Report
-----------
Name: \#(userName)
Logins: \#(loginCount)
Admin: \#(isAdmin)
Home Path: C:\Users\Ava
Validation Pattern: ^\w+$
"""#

print(report)

This example shows why raw strings are practical. You can keep the path and pattern readable, while still inserting real variable values with interpolation.

10. Key Points

11. Practice Exercise

Try this exercise to check your understanding.

Expected output: a short multiline message showing the user name and the exact path with backslashes preserved.

Hint: Use #""" for the multiline raw string and \#(user) for interpolation.

let folderPath = #"C:\Projects\SwiftApp"#
let user = "Lina"

let summary = #"""
User: \#(user)
Project Folder: C:\Projects\SwiftApp
"""#

print(summary)

12. Final Summary

Swift literals are the direct values you place in code, and string literals are one of the most common kinds you will use. Raw strings are a specialized but very practical form of string literal that help when normal escaping makes text hard to read. They are especially useful for quoted text, file paths, regex patterns, and large text blocks.

The most important idea to remember is that raw strings change parsing rules, not the final type. You still get a normal String, but you write it with clearer syntax for certain kinds of content. If you continue learning Swift strings next, a great follow-up topic is multiline strings, escape sequences, and string interpolation in more depth.