Swift Tutorial · Swift Basics · Lesson 3 of 30
Swift Syntax and Output
Statements, comments, print, and string interpolation for formatted output.
Basic syntax
- One statement per line; semicolons are only needed between statements on the same line.
//line comments and/* ... */block comments (which can nest).printtakes several items, aseparatorand aterminator(a new line by default).
// 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.
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?
${value}\(value){value}%value%
Show answer
Answer: \(value)