Line At A Time
Lesson 6: String Interpolation
String Interpolation Drop variables straight into text, the Swift way.
1let name = "Ada"
2let age = 10
3print("\(name) is \(age) years old")
Terminal
$ swift main.swift
Ada is 10 years old
Every line, explained
let name = "Ada"
let creates a constant: a named box whose value is set once and can never change. Swift people reach for let by default: if a value never needs to change, locking it down prevents accidents.
let age = 10
let creates a constant: a named box whose value is set once and can never change. Swift people reach for let by default: if a value never needs to change, locking it down prevents accidents. Numbers don't need quotes: Swift sees 10 and makes age an Int.
print("\(name) is \(age) years old")
Inside a Swift string, \(...) is magic: Swift swaps \(name) for the value of name. This is called string interpolation, and it is THE Swift way to mix variables into text. Here \(name) becomes Ada and \(age) becomes 10, much tidier than gluing with +.