Tuesday, January 31, 2017

Fun With Swift String Interpolation

Ole Begemann:

The source of the problem is that “unsafe strings” and “safe strings” are so fundamentally different that we should often treat them differently, yet we tend to use the same String type for both. So let’s introduce separate types for these concepts. I’m calling these UnsafeString and SanitizedHTML.

[…]

If we make sure that all rendering APIs only accept SanitizedHTML as input, the new types make it impossible to accidentally render an unescaped string.

[…]

Customizing how your own types interpret an interpolation string is an extremely powerful feature, especially for DSLs. Building SQL queries or localized strings are just two examples where you could employ the same techniques (here’s an implementation of the latter by Brent Royal-Gordon). Any task that needs strings built from components can probably profit from it.

Comments RSS · Twitter

Leave a Comment