NEW! Master Swift design patterns with my latest book! >>

How to create multi-line string literals

Paul Hudson       @twostraws

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.

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.

Take Swift further!

Your Swift skills let you make apps for macOS, watchOS, tvOS, and more, and for one low price you can learn it all with my Swift Platform Pack!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>