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 literal is written directly in code, such as 42, true, or "Hello".
  • A normal string literal uses quotes and standard escape rules.
  • A raw string literal uses # around the quotes, such as #"Hello"#.
  • Inside a raw string, backslashes are treated as plain characters unless you match them with the same number of # characters.
  • Raw strings are especially useful for regular expressions, Windows-style paths, JSON samples, and quoted text.

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 need to include quote characters without escaping every one.
  • You need literal backslashes, such as file paths or regular expression patterns.
  • You want to show source code or text exactly as written.
  • You still want string interpolation, but with clearer syntax.

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

Normal literals in Swift

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

Swift
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.

Swift
let name = "Mina"
let message = "Hello, \(name)!\nWelcome back."
print(message)
Output✓ Tested · Swift 6.4
Hello, Mina!
Welcome back.

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.

Swift
let path = #"C:\Users\Mina\Documents"#
print(path)
Output✓ Tested · Swift 6.4
C:\Users\Mina\Documents

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).

Swift
let city = "Seoul"
let text = #"Current city: \#(city)"#
print(text)
Output✓ Tested · Swift 6.4
Current city: Seoul

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.

Swift
let userName = "Ava"
let greeting = "Hello, \(userName)!"
print(greeting)
Output✓ Tested · Swift 6.4
Hello, Ava!

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.

Swift
let quote = #"She said, "Swift is readable.""#
print(quote)
Output✓ Tested · Swift 6.4
She said, "Swift is readable."

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.

Swift
let pattern = #"^\d{3}-\d{4}$"#
print(pattern)
Output✓ Tested · Swift 6.4
^\d{3}-\d{4}$

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.

Swift
let product = "Keyboard"
let price = 79
let label = #"Item: \#(product), Price: $\#(price)"#
print(label)
Output✓ Tested · Swift 6.4
Item: Keyboard, Price: $79

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.

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

print(jsonSample)
Output✓ Tested · Swift 6.4
{
  "name": "Ava",
  "role": "Developer",
  "path": "C:\Users\Ava"
}

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

5. Practical Use Cases

  • Storing regular expression patterns without excessive escaping.
  • Writing Windows-style file paths that contain many backslashes.
  • Embedding JSON or sample API payloads in test code.
  • Including quoted text in messages, logs, or generated content.
  • Showing code snippets as text output without Swift interpreting every backslash.
  • Writing multiline templates where readability matters more than compactness.

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.

Swift
let name = "Noah"
let message = #"Hello, \(name)!"#
print(message)
Output✓ Tested · Swift 6.4
Hello, \(name)!

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

Swift
let name = "Noah"
let message = #"Hello, \#(name)!"#
print(message)
Output✓ Tested · Swift 6.4
Hello, Noah!

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.

Swift
let title = #"Swift Raw Strings"##
Compiler output✓ Tested · Swift 6.4
error: too many '#' characters in closing delimiter

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

Swift
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.

Swift
let status = #"Ready"#

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

Swift
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.

Swift
let text = """
Path: C:\Users\Ava
Regex: \d+
"""
Compiler output✓ Tested · Swift 6.4
error: invalid escape sequence in literal

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

Swift
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.

Swift
// 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.

Swift
let value = "Swift"
let text = ##"This shows # and also interpolates: \##(value)"##
print(text)
Output✓ Tested · Swift 6.4
This shows # and also interpolates: Swift

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.

Swift
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

  • Raw strings only change how string content is parsed in source code. They do not create a different runtime string type; the result is still a String.
  • Interpolation is not disabled forever in raw strings. It just requires matching syntax such as \#(...) or \##(...).
  • If your text includes the exact raw-string delimiter sequence, you may need to increase the number of # characters.
  • Multiline raw strings still follow Swift's multiline string rules, including delimiter placement.
  • If a string seems to print \(name) literally instead of the value, the interpolation syntax probably does not match the raw string delimiter.
  • If you see an error like unterminated string literal, check that the opening and closing quotes and # characters match exactly.

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.

Swift
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)
Output✓ Tested · Swift 6.4
User Report
-----------
Name: Ava
Logins: 12
Admin: false
Home Path: C:\Users\Ava
Validation Pattern: ^\w+$

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

  • A literal is a fixed value written directly in Swift source code.
  • Strings can be written as normal string literals or raw string literals.
  • A raw string uses #"..."# and changes how escape sequences are parsed.
  • Raw strings are useful for quotes, backslashes, regex patterns, file paths, and embedded text.
  • Interpolation in a raw string must use matching syntax such as \#(...).
  • Raw strings improve readability when normal escaping becomes noisy.
  • The resulting value is still a normal Swift String.

11. Practice Exercise

Try this exercise to check your understanding.

  • Create a constant named folderPath that stores C:\Projects\SwiftApp using a raw string.
  • Create a constant named user with the value "Lina".
  • Create a multiline raw string named summary that includes the path and interpolates the user name.
  • Print the summary.

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.

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

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

print(summary)
Output✓ Tested · Swift 6.4
User: Lina
Project Folder: C:\Projects\SwiftApp

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.