[swift-evolution] Strings in Swift 4

Gwendal Roué gwendal.roue at gmail.com
Fri Jan 20 10:27:53 CST 2017


> One ask - make string interpolation great again?

I have a dream, that ExpressibleByStringInterpolation would allow to distinguish literal segments and embedded inputs.

Today, the documentation of this protocol [1] says:

	"One cookie: $\(price), \(number) cookies: $\(price * number)."
	// <=>
	let message = String(stringInterpolation:
		String(stringInterpolationSegment: "One cookie: $"),
		String(stringInterpolationSegment: price),
		String(stringInterpolationSegment: ", "),
		String(stringInterpolationSegment: number),
		String(stringInterpolationSegment: " cookies: $"),
		String(stringInterpolationSegment: price * number),
		String(stringInterpolationSegment: "."))

This means that ExpressibleByStringInterpolation can't distinguish "foo" from `bar` in "foo\(bar)".

If this distinction were possible, some nice features could emerge, such as context-sensitive escaping:

	// func render(_ html: HTML)
	let title = "<script>boom();</script>"
	render("<h1>\(title)</h1>") // escapes input
	
	// func query(_ sql: SQL)
	let name = "Robert'); DROP TABLE students; --"
	query("SELECT * FROM students WHERE name = \(name)") // avoids SQL injection

Ideally, a solution for multi-line literals (for strings and interpolated strings) would be found, too.

I wish the manifesto would address these topics as well :-)

Regards,
Gwendal Roué

[1] https://developer.apple.com/reference/swift/expressiblebystringinterpolation



More information about the swift-evolution mailing list