Swift5 to create a string from the original text

  • 2020-06-12 10:47:14
  • OfStack

preface

Creating Swift strings from raw text is often painful. Removing any quotation marks or backslash characters from the original text correctly is a frustrating exercise. Swift 5, released with Xcode 10.21, introduces a new syntax that makes it easier to use the original text.

Create a string using string literals

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


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

Custom string escape (Swift 5)

In Swift 5, SE-0200 allows you to customize delimiters and escape sequences. This is useful when dealing with raw text that may contain delimiters or escape sequences.
You can populate the start, end, and escape separator 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 do not need to escape the double quotes now because they are no longer delimiters. If our original text contains the delimiter we selected, we can populate it with the additional "#" :


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

If we populate the separator # with one or more separators, we also need to populate the backslash escape sequence. For example, in interpolation:


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

When a single fill is used, the # escape sequence becomes \# :


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

Custom delimiters are useful when we want to keep the escaped original text. For example, when String is created from some JSON. Using multi-line string literals seems like a good approach:


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

Multi-line string literals are handy when the text contains quotes, but in this case an error is introduced. The problem is that the compiler stripped the backslash, "title" resulting in 1 some invalid JSON:


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

If we use a custom delimiter with multi-line string literals, we can keep the escape sequence in the original text:


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

The generated String is preserved with the original text (note the backslash escaping the double quotation marks around the title) :


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

conclusion


Related articles: