|< Why do we need to mark some methods as mutating?||Why do strings behave differently from arrays in Swift? >|
In many other languages, strings aren’t structs – they are just a sequence of letters, and nothing more. Swift takes a different approach: strings are structs, and in fact come packed with functionality.
Almost all of Swift’s core types are implemented as structs, including strings, integers, arrays, dictionaries, and even Booleans. This isn’t an accident: structs are simple, fast, and efficient in Swift, which means we can create and destroy them as much as we need without worrying too much about performance.
However, strings are a particularly complicated problem to solve because language is complex. Yes, things like the English alphabet takes just 26 lowercase and 26 uppercase characters, but Swift also needs to be able to handle other scripts – Hebrew, Arabic, Cyrillic, Tamil, and many more. Heck, there are over 50,000 Chinese characters!
Where things get really complex is how we handle emoji, because there are countless variations for skin tone and gender. Rather than storing each emoji as a unique “letter”, these often broken down into multiple special letters. For example, the emoji “two women holding hands, where the the left woman has light skin tone and the right woman has medium-dark skin tone,” Swift actually stores:
So, we actually use seven “letters” to store one emoji in that instance – it’s complicated!
As a result, Swift encapsulates all the functionality to handle strings into the string themselves. This means we can use functionality such as the
count property without worrying about it miscounting emoji. The alternative would be to have hundreds of standalone functions to handle strings and their complexities, which wouldn’t be pleasant.
Now you understand some of the complexities of strings, take another look at these properties and methods:
print(string.count) print(string.hasPrefix("Hello")) print(string.uppercased()) print(string.sorted())
I hope you can see they do a heck of a lot of work on our behalf! Sorting a string with emoji would cause all sorts of problems if the individual characters inside the emoji were pulled apart. Fortunately, Swift’s strings are designed to take care of all this work for us, and although it causes a few road bumps here and there the overall benefit is massive.
SPONSORED ViRE offers discoverable way of working with regex. It provides really readable regex experience, code complete & cheat sheet, unit tests, powerful replace system, step-by-step search & replace, regex visual scheme, regex history & playground. ViRE is available on Mac & iPad.
Link copied to your pasteboard.