Strings & Interpolation
Almost every app shows text: names, addresses, prices, messages. In Swift, text is stored in a String, a sequence of Character values. Swift strings are fully Unicode, so Hindi, Tamil, the ₹ sign and accented letters all work without special effort.
In this lesson you will build strings with interpolation, write multi-line and raw strings, use the most common string methods, and learn why Swift does not let you write name[0].
String literals and interpolation
A string literal is text in double quotes. String interpolation inserts values into a string: write \( and ) around any expression, and Swift converts the result to text.
let name = "Farhan"
let city = "Lucknow"
let age = 21
print("Hi, I am \(name) from \(city).")
print("Next year I will be \(age + 1).")
let price = 45
let quantity = 4
print("Total: ₹\(price * quantity)")Hi, I am Farhan from Lucknow. Next year I will be 22. Total: ₹180
Interpolation works with any type: numbers, Bool values, and your own types. It is the normal way to build text in Swift, and it avoids the type errors you get when joining numbers to text with +.
Joining, counting and multi-line strings
var greeting = "Good"
greeting += " morning"
greeting = greeting + ", Kochi"
print(greeting)
print(greeting.count)
print("".isEmpty)
let address = """
Sharma Sweets
MI Road, Jaipur
Rajasthan 302001
"""
print(address)Good morning, Kochi 19 true Sharma Sweets MI Road, Jaipur Rajasthan 302001
+ joins two strings and += appends to a var. count gives the number of characters, and isEmpty checks for an empty string (it is clearer and faster than count == 0).
A multi-line string starts and ends with three double quotes on their own lines. The indentation of the closing """ decides how much leading space is removed from every line, so you can indent the text neatly with your code and still print it without the extra spaces.
Escape sequences and raw strings
Some characters cannot be typed directly inside quotes. You write them with a backslash escape sequence: \" for a double quote, \\ for a backslash, \n for a new line, \t for a tab and \u{...} for any Unicode character by its code.
let student = "Farhan"
print("She said \"Namaste\"")
print("Folder: C:\\Users\\\(student)")
print("Line one\nLine two")
print("Rupee sign: \u{20B9}")
print(#"A raw string keeps \n and "quotes" as they are"#)
print(#"Interpolation in a raw string: \#(student)"#)She said "Namaste" Folder: C:\Users\Farhan Line one Line two Rupee sign: ₹ A raw string keeps \n and "quotes" as they are Interpolation in a raw string: Farhan
A raw string is wrapped in #" and "#. Backslashes and quotes inside it are ordinary characters, which is very useful for regular expressions and Windows paths. To interpolate inside a raw string, add the same number of # signs after the backslash: \#(student).
Common string methods
Some useful methods come from the standard library and some from Foundation, Apple's basic library that is also available on Linux and Windows. Add import Foundation at the top of the file when you use them; SwiftUI apps import it automatically through import SwiftUI.
import Foundation
let station = " New Delhi Junction "
let clean = station.trimmingCharacters(in: .whitespaces)
print(clean)
print(clean.uppercased())
print(clean.lowercased())
print(clean.hasPrefix("New"), clean.hasSuffix("Station"))
print(clean.contains("Delhi"))
print(clean.replacing("Junction", with: "Jn"))
let average = 2.0 / 3
print(average)
print(String(format: "%.2f", average))New Delhi Junction NEW DELHI JUNCTION new delhi junction true false true New Delhi Jn 0.6666666666666666 0.67
Strings are values: methods like uppercased() return a new string and leave the original unchanged. String(format: "%.2f", x) (from Foundation) shows a Double with exactly two decimal places, rounded, which is what you want for prices and percentages.
Characters, indexes and substrings
You cannot write pnr[0] in Swift. The reason is Unicode: one visible character can take one to several bytes in memory, so finding "character number 3" means walking through the string. Swift makes that cost visible with String.Index instead of hiding it behind an Int.
let pnr = "PNR4521"
print(pnr.prefix(3))
print(pnr.suffix(4))
print(pnr.dropFirst(3))
let fourth = pnr[pnr.index(pnr.startIndex, offsetBy: 3)]
print(fourth)
for ch in pnr.prefix(3) {
print(ch, terminator: "-")
}
print()
let price = "₹500"
print(price.count, price.utf8.count)PNR 4521 4521 4 P-N-R- 4 6
prefix, suffix and dropFirst cover most everyday needs without indexes. When you do need a position, index(_:offsetBy:) moves from startIndex. A for loop visits each Character; here terminator: keeps the three letters on one line, and the plain print() after the loop ends that line. The last line shows the Unicode point: "₹500" has 4 characters but takes 6 bytes in UTF-8, because ₹ alone needs 3 bytes.
The results of prefix, suffix and split are of type Substring: a view into the original string that avoids copying. Convert one with String(...) when you want to keep it for long or pass it to a function that needs a String.
let csvLine = "Aarav,Priya,Kabir,Meera"
let names = csvLine.split(separator: ",")
print(names.count)
print(names[1])
let firstName = String(names[0])
print(firstName.count)
print(names.joined(separator: " | "))4 Priya 5 Aarav | Priya | Kabir | Meera
split(separator:) breaks a string into an array of substrings, and joined(separator:) does the opposite.
Common mistakes
- Trying
name[0]. Usename.first,prefix(1)orindex(_:offsetBy:). - Forgetting
import Foundationfor methods liketrimmingCharacters(in:)orString(format:)in a plain Swift file. - Keeping substrings for a long time. A
Substringkeeps the whole original string in memory; convert it withString(...). - Using
countto check for empty text. Writetext.isEmpty.
Key points
- Use interpolation,
"\(value)", to build text from values and expressions. - Multi-line strings use
"""; raw strings use#"..."#and interpolate with\#(...). - Escape sequences include
\",\\,\n,\tand\u{20B9}. count,isEmpty,uppercased(),hasPrefix,contains,replacingandsplitcover most daily work; some helpers need Foundation.- Strings are indexed with
String.Index, notInt, because characters vary in size. prefix,suffixandsplitreturnSubstringvalues; convert withString(...)to keep them.
Exercise
A college form gives a full name as " kabir singh rathore ". Remove the outer spaces, split it into words, and print: the number of words, the first name in capitals, and the initials joined with dots (for example K.S.R.). Hint: word.prefix(1).uppercased() gives the capital first letter of a word.
Show solution
import Foundation
let raw = " kabir singh rathore "
let words = raw.trimmingCharacters(in: .whitespaces).split(separator: " ")
print(words.count)
print(words[0].uppercased())
var initials = ""
for word in words {
initials += word.prefix(1).uppercased() + "."
}
print(initials)3 KABIR K.S.R.
split(separator: " ") gives three substrings. The loop adds the first letter of each word, in capitals, followed by a dot.
Quick Quiz
1. What does print("Total: \(2 * 60)") print?
Interpolation evaluates the expression inside \( ) and inserts the result.
2. Why can you not write name[0] for a Swift String?
Swift strings are fully Unicode, so positions are String.Index values.
3. What type does "a,b".split(separator: ",") contain?
split returns substrings that share storage with the original string.
4. How do you interpolate x inside the raw string #"..."#?
A raw string needs the same number of # signs after the backslash.
Learn Swift with a mentor
Free lessons get you started. Our Mobile App Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
