Swift Tutorial · Swift Basics · Lesson 3 of 30

Swift Syntax and Output

Statements, comments, print, and string interpolation for formatted output.

Create a free account to save this page, take notes and track your progress. Sign in

Basic syntax

  • One statement per line; semicolons are only needed between statements on the same line.
  • // line comments and /* ... */ block comments (which can nest).
  • print takes several items, a separator and a terminator (a new line by default).
print
// print with several items
print("Loading", terminator: "")
print("...", terminator: "")
print(" done")
print(1, 2, 3, separator: " - ")
print(3 * 7 + 1)

Output

Loading... done
1 - 2 - 3
22

Run this on your computer — see “Get Started” for setup.

String interpolation

\(expression) inserts any value into a string. String(format:) from Foundation formats numbers.

String interpolation
import Foundation

let name = "Ana"
let items = ["mug", "teapot"]
let balance = 1234.5678
print("\(name) has \(items.count) items")
print("First item: \(items[0].uppercased())")
print("Balance: \(String(format: "%.2f", balance)) EUR")

Output

Ana has 2 items
First item: MUG
Balance: 1234.57 EUR

Run this on your computer — see “Get Started” for setup.

Test yourself

How do you insert a value into a Swift string?

  1. ${value}
  2. \(value)
  3. {value}
  4. %value%
Show answer

Answer: \(value)

Was this page helpful?