Search code examples
stringdelimiterswift5rawstring

Enhancing String Literals Delimiters to Support Raw Text Swift


I recently found this code snippets on the Swift 5 Book.

print(#"Write an interpolated string in Swift using \(multiplier)."#)
// Prints "Write an interpolated string in Swift using \(multiplier).”

print(#"6 times 7 is \#(6 * 7)."#)
// Prints "6 times 7 is 42.”

I learnt it was an accepted proposal in Swift 5 for enhancing string literals delimiters to support raw text, with so many examples given.

My question is when and how is it used in practical cases because from the examples given above, I would still clearly achieve what I want to even without the # signs!


Solution

  • To give just one example where it is very useful. How about when writing Regex, previously it was a nightmare as you had to escape all special characters. E.g.

    let regex1 = "\\\\[A-Z]+[A-Za-z]+\\.[a-z]+"
    

    Can now be replaced with

    let regex2 = #"\\[A-Z]+[A-Za-z]+\.[a-z]+"#
    

    Much easier to write. Now when you find a regex online, you can just copy and paste it in without having to spend ages escaping special characters.

    Edit:

    Can read here

    https://www.hackingwithswift.com/articles/162/how-to-use-raw-strings-in-swift