Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Swift Basics  ›  Capstone Project

Comments and Semicolons

Comments 12 minComments are notes the compiler ignores and should explain why, while semicolons are only needed to separate two statements on one line.

Comments and Semicolons

Three weeks from now you will open Sprout's streak code and wonder why a missed day on a Sunday does not reset the streak. A one-line comment written today answers that in a second. Comments are notes for humans; the compiler ignores them. Semicolons, meanwhile, are something Swift mostly lets you forget.

The rule

Comments explain why; semicolons only join two statements on one line.

Swift has three comment styles:

// A single-line comment runs to the end of the line.

/* A block comment can run
   over several lines. */

/// Returns the streak after today's check-in.
/// Shown in Xcode's Quick Help for this function.
func nextStreak(from streak: Int) -> Int {
    streak + 1
}
  • // is for short notes.
  • /* */ wraps several lines. In Swift, block comments can nest: a /* */ inside another /* */ is fine, which makes it safe to comment out code that already contains one.
  • /// is a documentation comment. Xcode shows it when you Option-click the name it sits above.

Good comments say why, not what. streak += 1 // add one to streak repeats the code. // Weekends are optional in Sprout, so a Sunday miss keeps the streak saves the next reader real time.

Semicolons are optional at the end of a line. Swift code almost never uses them. They are needed only to put two statements on the same line:

let done = 3; let goal = 5

The shortcut

For comments, ask "could the reader get this from the code alone?" If yes, delete the comment. If no, it is worth keeping. For semicolons, ask "are there two statements on this line?" Only then is one required.

Tidying a Sprout fileStep 1 of 4
  1. var streak = 0;

    One statement on the line. The semicolon is legal but pointless. Remove it.

Nesting is a small Swift nicety: in C, a */ inside a block comment ends it early. In Swift, the comments pair up correctly.

Drills

Answer fast — trust the rule.

quick drill

When is a semicolon required in Swift?

quick drill

Which comment style appears in Xcode's Quick Help?

quick drill

Which is the more useful comment?

quick drill

What happens when a /* */ comment contains another /* */ comment in Swift?

Remember

  • Comments explain why; semicolons only join two statements on one line.
  • // for notes, /* */ for blocks (they nest), /// for Quick Help docs.
  • If the code already says it, the comment should go.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainReview these comments

A teammate wrote var streak = 0; // streak and streak += 1 // add 1. Review both lines: what would you change, and what kind of comment would actually help?