Welcome Guide to Swift 5 Escaping String

With the evolution of Swift, we often comes to create strings from raw text which can be a pain. Properly escaping any quotes or backslash characters in the raw text is an exercise in frustration.

Swift 5, introduced with Xcode 10.2, introduces a new syntax to make it easier to work with raw text.

Traditional Strings With String Literals

To create a String from literal text, we use the common method of double quote (") as a starting and ending delimiter and the backslash (\) to escape special characters. For example, to create a String that preserves the double-quotes in this text:

let title1 = "This is \"title\" here" // This is "title" here



Swift 5 Custom String Escaping

Swift 5 allows you to customize the delimiter and escape sequences. This is useful when working with raw text that might contain the delimiters or multiple escape sequence.
Here we can pad the start, end and escape delimiters with one or more “#” characters. These three examples all produce the same result:

let title2 = #"This is "title" here"# let title3 = ##"This is "title" here"## let title4 = ###"This is "title" here"###
Result: // This is "title" here

The reason this exists is so that strings end only when you want them to, so in the unlikely event that when you need to write ”# in a string you won’t hit problems.

For example, you’d need to write a string something like Swift Programming is #"amazing".
In this Twitter like string statement, I didn’t leave a space after the quote. Using a single-delimited raw string Swift would confuse compiler as a string terminator. So we can write this as

let myString = ##Swift Programming is #"amazing"##

Swift Evolution proposal that brought about raw strings: SE-0200

Comments

Popular posts from this blog

Java Program to implement binary checksum

Java Program for block parity