Swift version: 5.1
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.
LEARN SWIFTUI FOR FREE I have a massive, free SwiftUI video collection on YouTube teaching you how to build complete apps with SwiftUI – check it out!
Available from iOS 8.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.