Fun With Swift String Interpolation
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 theseUnsafeString
andSanitizedHTML
.[…]
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.