Swift version: 5.0
By default Swift strings can’t span more than one line. One simple way around this is to use the new line character
\n, but that only works for strings that are displayed – if you’re just trying to format your string nicely, you should use multi-line strings instead.
Multi-line strings work similarly to regular strings in that they support things like string interpolation, but they have the added benefit that they can be spread over as many lines as you need.
To start a string literal, you need to write three double quotation marks,
”””, then press return. You can then go ahead and write a string as long as you want, including variables and line breaks, before ending your string by pressing return then writing three more double quotation marks.
I've been specific about pressing return because string literals have two important rules: when you open a string using
""" the content of your string must begin on a new line, and when you end a multi-line string using
””” that must also begin on a new line.
Here it is in action:
let longString = """ When you write a string that spans multiple lines make sure you start its content on a line all of its own, and end it with three quotes also on a line of their own. Multi-line strings also let you write "quote marks" freely inside your strings, which is great! """
That creates a new string with several line breaks right there in the definition – much easier to read and write.
SPONSOR Tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize your debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically. It only takes a line of code to setup. Get started for free.
Available from iOS 8.0
Did this solution work for you? Please pass it on!
Other people are reading…
About the Swift Knowledge Base
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.