Multiline Strings in Swift
To define multiline strings in Swift, enclose the multiline string in triple double-quotes.
For example, consider the following code snippet, where we define a multiline string literal, and assign it to a variable x.
let message = """
This is first line.
This is second line.
This is third line.
"""
The multiline string starts from the first line after the opening triple quotes “”” and ends at the line before the closing triple quotes “””.
1. Define and print a multiline string literal
In the following example, we shall create a multiline string literal, and print it to standard output.
main.swift
let message = """
This is first line.
This is second line.
This is third line.
"""
print(message)
Output
2. Indent lines in multiline string literal
We can also provide an indentation to the lines in the multiline string literal to match the code indentation. Such indentation is ignored in the resulting string value.
main.swift
let message = """
This is first line.
This is second line.
This is third line.
"""
print(message)
Please observe that same indentation is given from starting line to last line, and also to the last triple quotes. If there is any addition space for any of the lines, that additional space appears in the resulting string.
Output
Conclusion
In this Swift Tutorial, we learned how to define a multiline string literal in Swift language, using triple quotes, with examples.