Skip to main content

Multi-line string literals

About 2 minSwiftArticle(s)bloghackingwithswift.comswiftswift-4.0

Multi-line string literals 관련

HACKING WITH SWIFT

What's new in Swift?

Multi-line string literals | Changes in Swift 4.0

Multi-line string literals

Available from Swift 4.0

Writing multi-line strings in Swift has always meant adding \n inside your strings to add line breaks wherever you want them. This doesn't look good in code, but at least it displays correctly for users. Fortunately, Swift 4 introduced new multi-line string literal syntax that lets you add line breaks freely and use quote marks without escaping, while still benefiting from functionality like string interpolation.

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.

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.

For more information see the Swift Evolution proposal for this new feature (apple/swift-evolution)open in new window.

Other Changes in Swift 4.0
Encoding and decoding data using Codable | Changes in Swift 4.0

Encoding and decoding data using Codable
Improved keypaths for key-value coding | Changes in Swift 4.0

Improved keypaths for key-value coding
Improved dictionary functionality | Changes in Swift 4.0

Improved dictionary functionality
Strings are collections again | Changes in Swift 4.0

Strings are collections again
One-sided ranges | Changes in Swift 4.0

One-sided ranges

Download Swift 4.0 playgroundopen in new window


이찬희 (MarkiiimarK)
Never Stop Learning.