Swift Strings
A string is a piece of text stored as a value. A string holds text that a program can print, join, and build from other values.
A string in double quotes
A variable can hold text as its value. The print shows the stored text exactly as written.
let city = "Paris"
print(city)Values placed inside text
The marks \(...) hold a spot for a value inside the text. The value is worked out and printed as part of the line.
let name = "Ana"
let score = 42
print("Hello, \(name)!")
print("\(name) scored \(score + 8) points")Joining strings with +
The + sign joins two strings end to end. The joined text prints as one line.
let first = "Hello, "
let second = "Ana"
print(first + second)Text across several lines
Three double quotes open and close a multiline string. Each line inside prints on its own line.
let card = """
Happy birthday, Ana.
Have a great day.
"""
print(card)Example
let player = "Ana"
let level = 3
print("Player: \(player)")
print("\(player) reached level \(level + 1)")Key points
- String literal: text written directly inside double quotes.
- Use \(...) inside a string to place a stored value in the text.
- Use + to join two strings into one longer string.
- Multiline literal: text written between two lines that each hold only three double quotes.
In this example, player holds the string Ana and level holds the number 3. The first print places player inside a label and shows Player: Ana. The second print places player and the sum level + 1 inside one string, so it shows Ana reached level 4.
Note
Placing a value inside a string needs no + sign and no type change.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
A program sets name to "Sam" and prints "Hi, \(name)!". What prints?