[swift-evolution] multi-line string literals

Brent Royal-Gordon brent at architechies.com
Fri Dec 11 16:10:12 CST 2015

> I would very much like to implement multi-line string literals in swift and get feedback on what this should look like, as i've been informed there are several competing suggestions filed as radars.

Some principles:

1. You do not want to plop enormous multi-line string constants in the middle of expressions. This makes the expressions impossible to read. Instead, you want a placeholder for the string in the expression, and then the string on a separate line.

2. Having said that, when there are several placeholders, you also want it to be obvious which text goes with which placeholder.

3. You want a syntax which clearly indicates which indentation is meant to line up the string literal with the code, and which is meant to be *in* the string literal.

With these principles in mind, I suggest something like:

	onMessage(DAVE>, sendMessage: HAL>)
	DAVE>Open the pod bay doors,
	HAL>I’m sorry, Dave,
	HAL>	I’m afraid I can’t 
	HAL>	do that.

A multiline literal reference consists of an identifier followed by a closing angle bracket in postfix operator position. After the end of any statement containing a multiline literal reference, Swift starts looking for the actual multiline literals mentioned in that statement. Leading whitespace is consumed and discarded up to a matching identifier and angle bracket; the text on the line after the literal, up to the newline, is the text of the literal. Once Swift encounters a line that doesn’t start with whitespace, an identifier, and an angle bracket, it switches back to looking for ordinary statements.

(By the way, the all-caps is a stylistic suggestion, not a requirement, and I’m not at all sure it’s the *right* stylistic suggestion.)

As a shorthand for lines with only one string, you might be able to say:

	>I’m sorry, Dave,
	>	I’m afraid I can’t
	>	do that.

While this solves the indentation problem, it doesn’t answer the question of whether the trailing \n is part of the literal. I think it is. I’m actually tempted to say that *all* newlines are ignored and you need \n if you want a real newline, but that seems like it would do a lot of violence to the entire concept of a multiline literal.

Brent Royal-Gordon

More information about the swift-evolution mailing list