How to declare multi-line string literal in swift with example

 Swift declare and create multi line string literal Examples

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"


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


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"
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.