Raw string literals: learning from Swift

Fred Curts fred.curts at icloud.com
Tue Jan 8 05:31:35 UTC 2019

I recently researched string literals for the sake of my own language experiment.
I looked at Java (proposal), Scala, Kotlin, Ceylon, Ruby, Python, Julia, Dart, JavaScript, Rust, Swift, C#, and possibly some other languages.

Swift's string literals came away as the clear winner for me, ticking all my boxes.

https://github.com/apple/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md (implemented in Swift 4)
https://github.com/apple/swift-evolution/blob/master/proposals/0200-raw-string-escaping.md (implemented in Swift 5)

Let me give some examples for why I think Swift's string literals are exceptionally well designed. In no particular order:

1. Multi-line and raw string literals are orthogonal features.
(Try adding a literal dollar sign to a Kotlin string literal spanning multiple lines and you'll know what I mean.)

2. Custom string delimiters solve all the use cases for raw string literals but nevertheless support escape sequences and interpolation expressions.
I've personally come across this need many times when trying to build larger regular expressions or code snippets out of smaller ones.

3. Escape sequences and interpolation expressions use the same escape character.
This simplifies matters considerably, in particular once custom string delimiters are added to the mix.
(Having multiple custom escape characters would be too much.)

4. Multi-line string literals are delimited by triple double quotes.
This makes them visually compatible with but heavier than single-line string literals, which seems like a good fit.
Distinct delimiters for single-line and multi-line string literals seem like a win for both humans and parsers.
For example, it's easy to tell where the missing end quote of a single-line string literal belongs.
5. It's easy to control line indentation of multi-line string literals and leading and trailing whitespace of the entire string.
All of this is settled at compile time.
6. Opening and closing delimiters of multi-line string literals must be on their own line.
This avoids headaches with edge cases such as string literals ending with two double quotes.

7. Multi-line string literals with custom string delimiters can contain arbitrarily long sequences of double quotes.

I hope I've convinced you that Swift's string literals are well worth a closer look.


More information about the amber-spec-observers mailing list