Skip to content
AgileLogics
5 min read

Strings

Prerequisites: Data types and type inference

A string is a piece of text: a sequence of characters in double quotes.

Syntax

let greeting = "Hello"

String interpolation

Put \(...) inside a string to insert any value — a variable, a calculation, even a function call:

let name = "Ada"
let age = 36

print("Hello, \(name)!")
print("Next year you'll be \(age + 1).")
print("Name has \(name.count) letters")
Hello, Ada!
Next year you'll be 37.
Name has 3 letters

Interpolation converts numbers to text for you. Joining with + only works between strings:

let first = "Ada"
let full = first + " Lovelace"
print(full)
Ada Lovelace

Special characters

  • \n — new line
  • \t — tab
  • \" — a double quote inside a string
  • \\ — a backslash

Multi-line strings

Three double quotes start and end a multi-line string. The closing """ sets the indentation — anything to its left is removed:

let name = "Ada"
let message = """
    Dear \(name),
    Thanks for signing up.
    """
print(message)
Dear Ada,
Thanks for signing up.

Common mistakes

  • Joining a string and a number with +: binary operator '+' cannot be applied to operands of type 'String' and 'Int'. Use interpolation: "Age: \(age)".
  • Using single quotes — they aren't valid in Swift.

Practice

Store a product name and a price, then print Coffee costs $3.5 using interpolation.

Show solution
let product = "Coffee"
let price = 3.5
print("\(product) costs $\(price)")