How to declare multi-line string literal in swift with example
In Swift, Normal strings are literals enclosed with double quotes.
if you declare a multi-line string literal with a double quote. It throws an error
var str:String = "first line
second line"
Output throws compilation error given below
main.swift:1:18: error: unterminated string literal var str:String = “first line ^ main.swift:2:32: error: unterminated string literal second line” ^ main.swift:2:27: error: consecutive statements on a line must be separated by ’;’ second line” ^ ; main.swift:2:21: error: cannot find ‘second’ in scope second line” ^~~~~~ exit status 1
How to create a multi-line string literal in Swift
With Swift version 3, You can declare the line break character appended with the second line as given below.
var str="first line\n" + "second line"
print(str)
Output:
first line
second line
Swift 4 version, you have to declare multi-line strings enclosed inside three double quotes.
let multilinestring = """
line one
line two
line three
line four
"""
print(multilinestring)
Output:
line one
line two
line three
line four
There are some important points
- multi-line strings content always starts in a new line
- three quotes must be in a new line at the start and end
How to include Html line break in swift
You can include html line break in multiple lines using the <br/>
tag.
var content = "line one<br />line two"