Using a Raw String to write JSON data
You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿
I think it’s quite obvious what needs to be improved with this code!
I’m using a literal string to define some JSON data.
But because a literal string considers the double quotes character as a special character, every time I use this character in the JSON, it needs to be explicitly escaped using a '\'
character.
As you can see, this introduces extra complexity and a lot of visual clutter.
Fortunately, Swift has the perfect feature to solve this issue!
By adding a '#'
character at the beginning and end of the literal string, we’re turning it into a raw string:
And as you can see, in a raw string we no longer need to escape double quotes characters, which makes the code much easier to read!
Even better, raw strings can also be used along with multiline strings, and the combination of the two is really powerful when you need to define large JSON data.
That’s all for this article, I hope that you’ve enjoyed discovering this little known feature of Swift, that’s actually been available for 5 years!
Here’s the code if you want to experiment with it:
// Regular String
import Foundation
let json = "{\"name\":\"Vincent\"}"
// Raw String
import Foundation
let json = #"{"name":"Vincent"}"#
// Raw + Multiline String
import Foundation
let json = #"""
{
"name":"Vincent"
}
"""#