Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 146 ยท Getting Started

Your First Swift Program

Write and run your first Swift program. Learn print, separators, comments, top-level code in main.swift and how the swiftc compiler builds your program.

Every language tutorial starts with "Hello, world", and Swift's version is one of the shortest in any compiled language: a single line, with no class, no main function and no imports. This lesson goes a little further than the one-liner. You will see how print really works, how comments are written, what "top-level code" means, what happens when the compiler finds a mistake and how a Swift file becomes a running program.

Hello, world

Swift Hello, Swift

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

print is a function from the Swift standard library, available in every file without an import. Text between double quotes is a string literal. Press Run and the text appears in the output panel, followed by a newline.

That is the whole program. In many languages you would need a class and a main method around it. Swift lets a file named main.swift contain top-level code: statements that run in order from the first line to the last, as if they were the body of a main function. Our runner compiles your code as main.swift, so everything you write here is top-level code.

print accepts any number of values. It converts each to text, separates them with a space and ends with a newline.

Swift Separators and terminators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Two argument labels change the behavior: separator: replaces the space between items and terminator: replaces the final newline. Calling print() with no arguments just prints a newline. Inside a string, a backslash starts an escape sequence: \n is a newline, \t a tab, \" a quote and \\ a backslash.

You will use print constantly, so it is worth knowing that it prints a value's description. Numbers and booleans look the way you expect. Optionals print as Optional(5) or nil, which is a handy clue that you forgot to unwrap something. See String Interpolation and Formatting for control over the output.

On a real machine print writes to standard output. To write to standard error you would use FileHandle.standardError from Foundation or the C library; we do that in Reading Input and Files and I/O. In this course's runner both streams show up in the same panel.

Comments

Comments are notes for people; the compiler ignores them.

Swift Three kinds of comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice that Swift block comments nest. That means you can comment out a stretch of code that already contains /* ... */ without breaking anything, which is not true in C or Java. Triple-slash /// comments are documentation comments; Documentation Comments shows the full syntax.

Write comments that explain why, not what. A comment that repeats the code ("add one to count") becomes a lie when the code changes.

Statements, semicolons and layout

Swift does not need semicolons. A newline ends a statement. You can put several statements on one line if you separate them with ;, but almost nobody does.

Swift code is indented with four spaces by convention, and the compiler does not care about indentation. Braces { } delimit blocks and are required for if, for, while and functions, which prevents the "forgot the braces" bug that has hit other languages.

Names are case-sensitive. Types use UpperCamelCase (String, BankAccount), everything else uses lowerCamelCase (print, totalPrice).

Top-level code and ordering

In main.swift, statements run top to bottom, so a variable should be declared before the code that uses it. Inside a function, the compiler enforces that:

Swift Using a local variable before its declaration (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with:

TEXT
main.swift:2:11: error: use of local variable 'total' before its declaration

The fix is to swap the two lines. Variables declared at the top level of main.swift are globals, and here Swift is more forgiving than you might want. A function declared in the file can read a global that has not been initialized yet, and it silently sees a zero value. Run this to see it:

Swift A global read too early

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first call prints total is 0, the second total is 5. The compiler does not catch this, so treat it as a rule: declare globals before any code that can run and read them. Better still, keep values in local scopes or pass them as arguments. Functions and types, unlike variables, can be used before their declaration in the file:

Swift Functions can come after their use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

In a larger project only one file may have top-level code (traditionally main.swift), or you mark a type with @main as the entry point. On Apple platforms an app's entry is usually the @main attribute on an App struct. Everything in this course uses top-level code because it keeps examples short.

What happens when you press Run

Under the hood, our server does roughly what you would do in a terminal:

Terminal
swiftc -swift-version 6 -O main.swift -o binary
./binary

This is a read-only illustration; you do not run it here. The first command is the compiler. It reads main.swift, checks types and safety rules, optimizes (-O) and produces a native executable. If it finds an error it prints messages and stops without producing a program. The second command runs the result.

-swift-version 6 selects the Swift 6 language mode, which includes strict data-race checking. That mode is why some concurrency examples later in the course fail to build until you fix the shared mutable state. On your own computer you can also type swift main.swift to compile and run in one step, or use swift run inside a Swift package. How Swift Works goes deeper.

Reading a compiler error

Let us make a typo deliberately.

Swift A misspelled function name (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The real output looks like this:

TEXT
main.swift:1:1: error: cannot find 'prnit' in scope

Learn to read three parts: the location (main.swift:1:1 is line 1, column 1), the severity (error stops the build; warning does not) and the message. Swift also prints the source line and a marker. When there are many errors, fix the first one and rebuild: later ones are often side effects.

Warnings are worth fixing too. For example, a variable declared with var that is never changed produces a warning suggesting let. Our test runs treat warnings as things to clean up.

Make it a habit to fix the first error first, and rerun. A single missing quote can cause a screen full of messages, all vanishing after one fix.

A slightly bigger program

Swift Bringing it together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Double(quantity) converts the integer to a Double; Swift never mixes Int and Double implicitly. We will return to that rule in Basic Types and Working with Numbers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does print("a", "b", separator: "-") output?

    The separator argument replaces the default single space between items, so the output is a-b followed by a newline.
  2. 2. Which statement about Swift block comments is true?

    Swift supports nested block comments, so commenting out code that already contains a block comment is safe.
  3. 3. A function in main.swift reads a global declared later in the file and is called before that line runs. What does it see?

    Top-level code runs in order. The compiler does not catch this case for globals, so the function sees zero until the declaration runs. Locals inside a function are checked by the compiler.
  4. 4. What does the -O flag of swiftc do?

    -O enables optimizations; -o names the output file. They are different flags.
  5. 5. Which part of 'main.swift:1:1: error: cannot find prnit in scope' is the location?

    The file name, line and column come first, then the severity and the message.

Summary

  • print(...) writes values to standard output; separator: and terminator: change spacing and the final newline.
  • In main.swift, top-level code runs from the top; declare variables before use (locals are checked, globals are not).
  • Comments: //, nestable /* */, and /// documentation comments.
  • Swift needs no semicolons, and braces are always required for blocks.
  • The compiler (swiftc) turns source into a native executable and reports errors with file, line and column; fix the first error first.

Next: How Swift Works