Escaping and Trimming Strings in Swift

In this article, we'll look at how to escape characters and trim strings in Swift.

Escaping Characters

In Swift, strings are defined by enclosing text in double quotes (").

If you want to use double quotes inside a string literal, you need to escape them.


In Swift, you use a backslash (\) to escape special characters.

To include a double quote in a string, place a backslash before it: \".

To include a backslash itself, escape it with another backslash: \\.

let s1 = "Double quote \" inside a string."
let s2 = "Backslash \\ inside a string."

print(s1)
print(s2)

The output shows that the escape backslash are removed, and the double quote and backslash appear as expected:

Double quote " inside a string.
Backslash \ inside a string.

Inserting Line Breaks and Tabs

You may want to insert tabs or line breaks into a string.

To insert a tab, use \t. To insert a line break, use \n, \r, or \r\n.

Note that line break codes differ depending on the system: \n on Unix and macOS, \r\n on Windows, and \r on older versions of macOS.


Here's an example with \t and \r\n:

print("aaa\tbbb\tccc")
print("-------------------")
print("xxx\r\nyyy\r\nzzz")

The output looks like this. Tabs may not be clearly visible in Playground, but if you paste the result into an editor like TextEdit, you'll see both the tabs and line breaks applied:

aaa	bbb	ccc
-------------------
xxx
yyy
zzz

Escaping and Trimming Strings in Swift 1


Trimming Strings

In programming, removing whitespace or other characters from the beginning and end of a string is commonly called "trimming".

In Swift, you can use the trimmingCharacters() method to trim strings.

This method takes a CharacterSet such as .whitespaces or .whitespacesAndNewlines as its argument and returns a trimmed string.


Let's try trimming a string using trimmingCharacters().

Since trimmingCharacters() comes from NSString, you'll need to import Foundation.

import Foundation

let s = "   Test  "
let trimmed = s.trimmingCharacters(in: .whitespaces)

print("[\(s)]")
print("[\(trimmed)]")

The output looks like this. The square brackets [ ] show that the surrounding spaces have been removed:

[   Test  ]
[Test]

That's it for escaping and trimming strings in Swift.