Bad practice: not using multiline strings


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 🍿


At first glance, this code seems very reasonable:

We want to display a string over two lines, and so we use the special character “\n” to represent the new line.

However, using this special character has the drawback of making the string harder to read.

And this becomes even more of a problem if we need to add more and more additional new lines…

But as it turns out, Swift actually has a much better solution for this problem!

Because instead of using the special character “\n”, we can use a feature called multiline string.

It’s very easy to use: we just need to declare our string with three double quotes instead of a single one.

This simple change has turned our string into a multiline string, which allows us to directly lay out the content of the string across several lines in our source code.

And as a result, the code has become much easier to read!

That’s all for this article, I hope this nice trick will come in handy for you soon!

Here’s the code if you want to experiment with it:

let string = """
1st line
2nd line
3rd line
4th line
"""
Previous
Previous

How to write tests that detect memory leaks 💦

Next
Next

Hidden feature: enum