Swift, lesson 1
Every program needs a way to show you what it's doing. In Swift that is the print() function.
Give it a value and it writes that value to the screen, then moves to a new line.
Text inside double quotes is a string. Swift strings always use double quotes; single quotes are not allowed. Notice there is no semicolon at the end of each line. Swift only needs a semicolon when you squeeze two statements onto the same line, and most people never do that.
print() accepts several values separated by commas. By default it puts a single space between
them:
Two optional, labelled arguments change how the pieces are joined:
separator: is what goes between the values (a space by default).terminator: is what goes after the last value (a new line, "\n", by default).The labels matter: Swift reads separator: and by name, so you must spell them out.
You will see a lot more of these named arguments when you write your own functions later.
2 exercises to try what you just read.
terminator:Anything after // on a line is a comment. Swift ignores it. Comments are notes for the
people reading your code, including future you. For longer notes, wrap the text in /* and */.
Unlike some languages, Swift lets you put one block comment inside another, which is handy when
you want to switch off a chunk of code that already contains a comment.
Your code lives in a file called main.swift. Swift treats the statements at the top level of
that file as the program: it runs them in order, from the first line to the last. There is no
main function to write.
Swift is a compiled language. Before anything runs, the compiler reads the whole file and
checks it. If you misspell print, forget a closing quote, or use a label wrongly, you get a
compile error and nothing runs, not even the lines above the mistake. The error message names
the line and usually suggests a fix, so read it carefully. Once the file compiles, the program
starts at the top.
Write a program that prints exactly these two lines:
The program reads no input.
Print a rocket countdown on a single line. Use one print() call with the three values
3, 2 and 1, joined by " - " and ending with "..." instead of a new line. Then use a
second print() call for Liftoff!.
Expected output:
print("Hello, World!")
print("Swift runs this line second.")print("Total:", 42) // Total: 42
print(3, "apples and", 5, "pears") // 3 apples and 5 pearsprint("2026", "11", "09", separator: "/") // 2026/11/09
print("Loading", terminator: "...")
print("done") // Loading...done// This line is ignored
print("This line runs") // a comment can also follow code
/* A block comment
can span several lines. /* It can even nest. */ */Hello, World!
I am learning Swift.3 - 2 - 1...Liftoff!