Can a Swift statement be broken over multiple lines?

Viewed 272

The language guide says:

Swift doesn’t require you to write a semicolon (;) after each statement in your code, although you can do so if you wish. However, semicolons are required if you want to write multiple separate statements on a single line.

This implies that Swift uses newlines as statement terminators. Does every statement need to fit on a single line? Or is it possible to insert a newline within a single statement - and if so, what are the rules that determine whether or not a newline terminates a statement?

1 Answers

Swift can have newlines in statements. It is so common in complex commands like this:

 var query = HouseholdInfoTable.table
        .select(HouseholdInfoTable.uuid.distinct, HouseholdInfoTable.table[*])
        .join(PersonInfoTable.table, on: PersonInfoTable.householdUuid == HouseholdInfoTable.uuid)
        .filter(HouseholdInfoTable.houseNumber == houseNumber)
        .order(HouseholdInfoTable.sortName)

But you can have simple statements broken up, like this:

let a = 1
 + 2
let b = 1 +
2

Generally you can split the line across operands or punctuation

You can do multiline comments with line feeds in them like this:

let bigComment = """
anythingYou want can go here
asdlkasdkljfad
askjf
"""

Swift's style guid has more in-depth information: https://google.github.io/swift/#line-wrapping

Playgrounds are a good place to see what the compiler handles.

Related