Semicolons in Swift

By

Learn why semicolons are optional in Swift, and the one case where you actually need one: writing more than one statement on the same line of code.

~~~

This tutorial belongs to the Swift series

In Swift, semicolons are optional. The end of the line is enough for the compiler to know where a statement ends. There’s one exception, and we’ll get to it in a moment.

You can write statements on separate lines, and you don’t need to add a semicolon:

let list = ["a", "b", "c"]
var a = 2

You can add a semicolon, but it adds nothing meaningful in this case:

let list = ["a", "b", "c"];
var a = 2;

The convention in the Swift community is to omit them. If you come from JavaScript, C or Java, your muscle memory will probably add them for a while. The compiler won’t complain. But linters like SwiftLint will flag trailing semicolons and ask you to remove them, because nobody writes Swift that way.

When do you need a semicolon?

If you want to write more than one statement on the same line, then you need to add a semicolon between them:

var a = 2; let b = 3

The semicolon here does the job the line break normally does: it tells the compiler where one statement ends and the next begins.

If you forget it, the code won’t compile. The compiler stops you with a clear message:

error: consecutive statements on a line must be separated by ';'

So there’s no risk of two statements silently merging into something unexpected. Either you separate them, or the compiler refuses the code.

Should you ever do this?

Rarely. Two statements on one line make sense when you’re experimenting in a playground and want to keep a quick test compact. In real code, I don’t use it.

My advice: one statement per line, no semicolons. It’s the style you’ll find in Apple’s documentation, in the Swift standard library, and in every Swift codebase you’ll read. Save the semicolon for the one case where the compiler asks for it.

Tagged: Swift · All topics
~~~

Related posts about swift: