Skip to Content
Course content

9: String Interpolation and Manipulation

Click on the "Edit" button in the top corner of the screen to edit your slide content.

How do I plug variables directly into a string without using a bunch of plus signs?

If you're coming from other languages, you might be tempted to use the + operator to glue strings together. In Swift, we call that concatenation, and honestly, it gets ugly fast once you have more than two variables. Instead, we use string interpolation.

You just wrap your variable or expression in \( ) inside the double quotes. Swift handles the conversion to a string for you automatically. I use this constantly for things like debugging logs or dynamic UI labels.

let username = "CyberKnight_99"
let level = 42
let health = 85.5

// Instead of "User: " + username + " Level: " + String(level)...
let statusReport = "Player: \(username) | Level: \(level) | HP: \(health)%"
print(statusReport) 
// Output: Player: CyberKnight_99 | Level: 42 | HP: 85.5%

One little trick: you can actually put basic math or logic inside those parentheses. Just don't go overboard, or your code becomes a nightmare to read. Keep it simple.

What's the best way to clean up messy user input, like accidental spaces or weird casing?

Users are unpredictable. They'll add a trailing space to their email address or accidentally hit Caps Lock. If you try to compare "User@Email.com" with "user@email.com", Swift will tell you they aren't the same because strings are case-sensitive.

To fix this, I usually chain a few manipulation methods together. trimmingCharacters(in:) is your best friend for removing that invisible whitespace at the start or end, and lowercased() ensures your comparisons are consistent.

let rawInput = "  SwiftLearner@Example.com  "

// Chain them together for a clean result
let sanitizedEmail = rawInput
    .trimmingCharacters(in: .whitespacesAndNewlines)
    .lowercased()

print("'\(sanitizedEmail)'") 
// Output: 'swiftlearner@example.com'

Can I easily swap out a specific word or phrase within a larger string?

Sometimes you have a template string—maybe a notification message—and you need to swap out a placeholder for real data. While interpolation is great for building a string from scratch, replacingOccurrences(of:with:) is the way to go when you're modifying an existing string.

I find this particularly useful when handling localized strings or templates coming from a server.

var welcomeMessage = "Hello [Name], you have [Count] new notifications!"

let personalizedMessage = welcomeMessage
    .replacingOccurrences(of: "[Name]", with: "Sarah")
    .replacingOccurrences(of: "[Count]", with: "7")

print(personalizedMessage) 
// Output: Hello Sarah, you have 7 new notifications!

Just a heads-up: replacingOccurrences returns a new string. It doesn't change the original one in place unless you assign it back to a var.




📋 Practical Task

Exercise: The Social Media Bio Formatter

You are building a profile editor. You've received a "raw" bio from a user that is messy and contains a placeholder tag. Your goal is to clean it up and format it for the public profile.

The Requirements:

  • Start with this variable: let rawBio = " I love coding in Swift and living in [City]! "
  • Remove the leading and trailing whitespace.
  • Replace the [City] placeholder with your actual city (or any city of your choice).
  • Convert the entire string to uppercase to make it a "shouting" bio.
  • Finally, use string interpolation to print the result inside this sentence: "User Bio: [Your cleaned string here]"
Rating
0 0

There are no comments for now.

to be the first to leave a comment.