Swift Basics: String Interpolation

While we've already looked at how to type string values directly into our code, Swift has a powerful feature called String Interpolation. This feature makes your strings incredibly useful by allowing you to inject variables directly inside them.

You can place almost any type of variable inside a string. To do this, simply write a backslash \ followed by your variable name wrapped in parentheses (), like this: \().

Swift
var healthPoints = 100
var statusMessage = "You currently have \(healthPoints) HP."

// statusMessage will output: "You currently have 100 HP."
You can do this as many times as you want, and even use strings to build other strings!

Swift
var battleLog = "Attention player: \(statusMessage)"
As we'll see shortly, string interpolation isn't just limited to placing variablesyou can actually execute Swift code directly inside those parentheses.

Why Does Swift Have String Interpolation?
When displaying information to your userswhether it's a printed console message, the text on a button, or personalized data for your appyou rely heavily on strings.

Naturally, we don't just want static, unchanging text; we want to show users relevant data that adapts to them. Swift provides string interpolation as a seamless way to insert custom data into your strings at runtime. In short, it dynamically replaces parts of your string with the live data you provide.

Swift
var username = "Alice"
var welcomeMessage = "Welcome back to the app, \(username)!"
Sure, we could have manually typed "Welcome back to the app, Alice!". However, in a real-world application, this dynamic insertion is crucial. It allows you to display live, actual user data rather than hardcoded text you typed yourself.

Swift lets you place all sorts of data types inside string interpolation. While the printed result of highly complex custom objects might not always look pretty, the output for all of Swift's basic types (Strings, Integers, Booleans, Doubles, etc.) is perfectly formatted.

More Examples:

Swift
// 1. Combining Strings
var title = "Captain"
var lastName = "Kirk"
var fullName = "\(title) \(lastName)"

// 2. Using Booleans
var isSubscribed = true
var accessStatus = "User active subscription: \(isSubscribed)"

// 3. Using it dynamically in a loop
let inventory = ["Sword", "Shield", "Health Potion", "Magic Map"]
var index = 0

// Loop through the inventory until the end
while index < inventory.count {
    print("Slot \(index + 1) contains a \(inventory[index]).")
    index += 1
}
Using Operators Inside String Interpolation
One of the best parts about string interpolation is that it can evaluate expressions. You can actually perform math and use operators right inside the string!

Swift
var itemPrice = 15
var quantity = 3

let receipt = "You bought \(quantity) items at $\(itemPrice) each. Your total comes out to $\(itemPrice * quantity)."

// Output: "You bought 3 items at $15 each. Your total comes out to $45."

댓글

이 블로그의 인기 게시물

How to Open, Set, and Save Environment Variables (Windows, macOS, Linux)

How to Fix Auto Layout Constraint Conflicts and Spacing Issues (Question, Image, and Options)

How to Fix Shared Progress Issues Across Different Difficulty Levels in SQLite