magnuskahr

writing code

Overview: Raw Strings

I keep forgetting how raw strings work in Swift, so by writing about it I hope to remember it - or at least remember that I have written about it and can look it up again.

Raw strings in Swift make it easier to work with escaping of typical characters. As we usually write strings as "Hello World" we face issues if we wanna have the character" itself in the string. We can escape this by using a backslash "\"", but this becomes rather complicated if we need to escape many times in a single string.

In the following, I am gonna list a few capabilities of raw strings and how it is used, but for a deeper dive, I advise reading How to use raw strings in Swift 5 on Hacking With Swift.

Creation of a raw string:

let html = #"<a href="https://magnuskahr.dk">My Website</a>"#

A raw string with string interpolation:

let name = "Magnus"
let greeting = #"Hello \#(name)"#

Raw strings can also support multi-line strings:

let paragraph = #"""
1. Do the dishes
2. Take out the trash
"""#

And finally, for edge cases with raw strings that contain"# itself, we can add several # to the start and end of the string:

let password = ###"AF67-A"##-23AM"###

Raw strings are a great tool to use and can greatly simplify your code when you need to escape characters.