In Swift you can create a String by sandwiching it between quotation marks:
let myString = "This is a string"
Starting with Swift 5, you can also create what is called a
raw string by adding the pound (hashtag) sign:
let myRawString = #"This is a raw string"#
raw string is useful because it treats the string as a raw list of characters. It doesn’t do anything fancy by default: no string interpolation, and no interpreting of special characters like
If you try to use string interpolation in a
raw string, here’s what you would see.
let pairsOfShoes = 34 let myString = "Alysha has \(pairsOfShoes) pairs of shoes." let myRawString = #"Alysha has \(pairsOfShoes) pairs of shoes."# print(myString) // Output: Alysha has 34 pairs of shoes. print(myRawString) // Output: Alysha has \(pairsOfShoes) pairs of shoes.
Notice how the string replaced
pairsOfShoes with its value, while the
raw string printed the string character by character.
If you add special characters into a raw string, it does something similar:
let myString = "Alysha \nloves\nshoes." let myRawString = #"Alysha \nloves\nshoes."# print(myString) // Output: Alysha loves shoes. print(myRawString) // Output: Alysha \nloves\nshoes.
raw string may not perform string interpolation by default, but it is possible if you add another pound sign to the string interpolation syntax:
let pairsOfShoes = 34 let myRawString = #"Alysha has \#(pairsOfShoes) pairs of shoes"# print(myRawString) // Output: Alysha has 34 pairs of shoes.
A common use case for
raw string is when you store a regular expression (regex) in your code. Because regexes often have many characters you would have to intentionally escape in a traditional string, a
raw string would make your code more simple and readable:
let myRawString = #"(?i)(<title.*?>)(.+?)()"# print(myRawString) // Output: (?i)(<title.* )(.+?)()
You may never use
raw string, but it is a good thing to know about as you read other people’s code. If you come across strings surrounded by pound signs, you’ll be able to recognize it’s a
raw string. Additionally, it’s a good tool to have in your back pocket for the day you work on a code base that uses regular expressions.