Multi-Line Strings in Swift 4

The beta for Swift 4 is out and it’s mostly an update to Swift 3.1 rather than a dramatic change like Swift 3.0 was to Swift 2.2. One of the simplest changes in Swift 4 is the way Swift now handles multi-line text. In the past, you had to laboriously create multiple lines of text using the next line or new line character (\n) like this:

var str = "This is an example\nof a multi-line text"

print (str)

The above code would print:

This is an example

of multi-line text

Of course, inserting \n characters everywhere can be ugly and tedious. That’s why Swift 4 now offers a simpler solution.

To identify multi-line text, start with a triple quotation mark symbol. Then type as much text as you want. Finally, identify the end of your text with another triple quotation mark symbol like this:

var newString = """
This is an example
of multi-line text

print (newString)

This code also prints:

This is an example

of multi-line text

The big difference is that you don’t have to worry about typing or forgetting to type the \n characters. This seemingly simple change is minor, but does show how Swift 4 looks for ways to improve the Swift language and make it easier to use.

Expect Apple to keep updating and refining Swift. There will never be drastic changes like the shift from Swift 2.2 to Swift 3.0, but expect more pleasant improvements in Swift 4 coming soon this fall.

July 5th, 2017 by
HTML Snippets Powered By :