SoFunction
Updated on 2025-04-09

Methods to create strings from original text in Swift5

Preface

Creating Swift strings from raw text is often painful. Correctly removing any quotes or backslash characters from the original text is a frustrating exercise. Swift 5, released with Xcode 10.2, introduced a new syntax to make it easier to use original text.

Create a string using string literal

When creating a string from a text text, use double quotes (") as the start and end delimiter and backslash (\) to escape special characters. For example, to create a String that retains double quotes in this text:

let title1 = "Insert \"title\" here"
// Insert "title" here

Custom string escape (Swift 5)

In Swift 5,SE-0200Allows you to customize delimiters and escape sequences. This is useful when dealing with original text that may contain delimiters or escape sequences.
You can fill in the start, end and escape separators with one or more "#" characters. All three examples produce the same result:

let title2 = #"Insert "title" here"#
let title3 = ##"Insert "title" here"##
let title4 = ###"Insert "title" here"###
// Insert "title" here

Note that we don't need to escape double quotes now, as they are no longer delimiters. If our original text contains the delimiter of our choice, we can populate it with an extra "#":

// raw text is "#Hello#"
// start delimiter is ##"
// end delimiter is "##
let regex1 = ##""#Hello#""##
// "#Hello#"

If we fill the delimiter # with one or more delimiters, we also need to fill the backslash escape sequence. For example, when interpolation:

let name = "Tom"
let greeting1 = "Hello \(name)" // Hello Tom

When using a single padding, the #escape sequence becomes \#:

let greeting2 = #"Hello \#(name)"# // Hello Tom

Custom delimiters are useful when we want to preserve escaped original text. For example, when creating a String from some JSON. Using multi-line string literals seems like a good way to do it:

let json1 = """
{
 "colors": ["red","green","blue"],
 "label": "Insert \"title\" here"
}
"""

Multiline string literals are convenient when the text contains quotes, but in this case an error is introduced. The problem is that the compiler strips the backslash, and the "title" causes some invalid JSON:

{
 "colors": ["red","green","blue"],
 "label": "Insert "title" here"
}

If we use a custom delimiter with multiline string literals, we can preserve the escape sequence in the original text:

let json2 = #"""
{
 "colors": ["red","green","blue"],
 "label": "Insert \"title\" here"
}
"""#

The generated String has the preserved original text (note the backslashes escaped double quotes around the title):

{
 "colors": ["red","green","blue"],
 "label": "Insert \"title\" here"
}

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.