Skip to Content
Course content

62: Working with Strings in Depth

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

Imagine you're holding a handmade friendship bracelet. Some of the beads are just single letters, but others are complex charmsβ€”maybe a little gold heart that's actually made of three tiny soldered pieces, or a specialized bead that combines two colors into one visual element. If I told you to "find the 5th bead," you'd just count them: one, two, three, four, five. But if I told you to "jump to the 5th millimeter of the string," you'd be lost. Why? Because beads aren't all the same width. One "visual" character might take up way more physical space on the string than another.

This is exactly why Swift handles strings the way it does. In many older languages, a string is just an array of bytes or characters, and you can jump to index 5 because every character is assumed to be the same size. But Swift uses Extended Grapheme Clusters. To Swift, a "character" is whatever the user perceives as a single character, regardless of how many Unicode scalars are hiding under the hood. An emoji like πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ looks like one character to you, but it's actually a sequence of multiple emojis joined by invisible "Zero Width Joiners."

The Frustration of String.Index

If you've tried to access a character in a Swift string using an integer, you've probably already seen the compiler scream at you. You can't do myString[5]. I know it feels tedious at first, but it's there to prevent your app from crashing when it hits a complex Unicode character that doesn't align with a simple integer count.

To move around a string, you have to use String.Index. Think of this as your finger sliding along that friendship bracelet. You start at the beginning, and you move one "bead" at a time.

let message = "Swift is πŸš€"
let start = message.startIndex
let thirdCharIndex = message.index(start, offsetBy: 2)
print(message[thirdCharIndex]) // This prints 'i'

I've found that the most common way to actually use this in the real world is by combining it with a loop or a range. You rarely need to manually calculate indices unless you're doing something very specific, like parsing a custom file format.

Slicing and the Substring Memory Trap

When you take a "slice" of a stringβ€”say, by using a range of indicesβ€”Swift doesn't actually create a brand new string. Instead, it gives you a Substring. This is a performance optimization. The Substring points back to the original string's memory to avoid expensive allocations.

Here is where I've seen a lot of developers get bitten: if you have a massive 10MB string and you create a tiny 5-character Substring from it, that entire 10MB string stays in memory as long as that substring exists. If you plan on keeping that slice around for a while, you must convert it back into a full String.

let longBio = "This is a very long user biography that takes up a lot of space..."
let summaryIndex = longBio.index(longBio.startIndex, offsetBy: 10)
let summarySlice = longBio[...summaryIndex] // This is a Substring

// Convert it to a String to let the large 'longBio' be garbage collected
let finalSummary = String(summarySlice)

Handling Complex Character Manipulation

Because strings are so complex, Swift provides a set of powerful methods that handle the index math for you. Instead of manually calculating indices to remove a character, you can use replacingOccurrences or work with the string as a collection.

If you need to check if a string starts or ends with something, never try to manually check the first index. Use the built-in methods. They are optimized for Unicode and far less prone to "off-by-one" errors that haunt us software engineers.

let filename = "profile_picture.png"
if filename.hasSuffix(".png") {
    print("This is an image file!")
}



πŸ“‹ Practical Task

Build a Social Media Handle Truncator

In this exercise, you will create a function that safely truncates a user's display name for a UI badge. The catch is that names often contain emojis, and you must ensure you don't cut the string in a way that leaves a trailing ellipsis if the name is already short enough.

Requirements:

  • Create a function called truncateDisplayName(_ name: String, limit: Int) -> String.
  • If the string's character count is less than or equal to the limit, return the name as-is.
  • If the string exceeds the limit, truncate it exactly at the limit and append "..." to the end.
  • Ensure you are using String.Index to perform the truncation.
  • Test your function with a string containing multi-scalar characters, such as: "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ Family & Friends" with a limit of 5.

Expected Output for "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ Family & Friends" (limit 5): "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ Fa..." (Note: The family emoji counts as 1 character, not 4 or 7!)

Rating
0 0

There are no comments for now.

to be the first to leave a comment.