Friday, December 28, 2018 [Tweets] [Favorites]

Swift 5: Raw String Literals

SE-0200:

Escape characters provide useful and necessary capabilities but strings containing many escape sequences are difficult to read. Other languages have solved this problem by providing an alternate “raw” string literal syntax which does not process escape sequences. As the name suggests, raw string literals allow you to use “raw” text, incorporating backslashes and double quotes without escaping.

We propose to alter Swift’s string literal design to do the same, using a new design which we believe fits Swift’s simple and clean syntax. This design supports both single-line and multi-line string literals, and can contain any content whatsoever.

Erica Sadun:

Those extra pounds allow you to change the way Swift interprets escape sequences. They transform escapes from simple backslashes to \#. To insert a newline into a pound-delimited string, you type \#n and not \n. Similarly, string interpolation becomes \#(...interpolation...).

This system was inspired by the Rust programming language. Rust stacks one or more pounds at each end of a string (and prefixes the letter “r”) to create what it calls “raw strings”, that is strings without further escape sequence interpretation. You cannot incorporate interpolation or coded tabs, new lines, or returns.

Swift adopts the extensible delimiters (skipping the ugly “r”) but retains its useful escapes, including string interpolation. Swift adapts each escape sequence to match the number of pound signs used at the start and end of the string. Instead of “raw strings”, Swift has, well, let’s call them “medium rare strings”. It allows you to paste and preserve raw formatting while retaining the ability to insert escape sequences.

Update (2019-02-21): Erica Sadun:

The development, refinement, and deployment of SE-0200 Enhancing String Literals Delimiters to Support Raw Text was a long and surprising journey. It ended with a uniquely Swift take on “raw strings” that focused on adding custom delimiters to string literals and escape sequences.

This post discusses what raw strings are, how Swift designed its take on this technology, and how you can use this new Swift 5 feature in your code.

Comments

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment