Mike Ash’s Friday Q&A this week takes on Swift’s funny-looking String API. Most of what you’d normally want to do with strings is absent — for the time being, we should be using NSString methods — and it doesn’t allow us to iterate over its characters in the way we’d expect. As of Swift 2.0, we can’t do:

for char in "some string" { /* ... */ }

That’s because there are several ways to interpret the above code — do we want to iterate over all bytes in the string, assuming it’s represented as UTF-8? All Unicode code points? All grapheme clusters? The String API’s design in Swift 2 forces the developer to explicitly decide by exposing these possibilities as views on the string, leaving the system’s internal representation of the string as an invisible implementation detail.

From Mike’s post:

Swift’s String type takes an unusual approach to strings. Many other languages pick one canonical representation for strings and leave you to fend for yourself if you want anything else. Often they simply give up on important questions like “what exactly is a character?” and pick something which is easy to work with in code but which sugar-coats the inherently difficult problems encountered in string processing. Swift doesn’t sugar-coat it, but instead shows you the reality of what’s going on. This can be difficult, but it’s no more difficult than it needs to be.

This is an excellent companion to objc.io‘s must-read NSString and Unicode showing the implications for Swift.

If you want the Cole’s Notes version, Apple has a pretty good, much shorter explainer on their Swift blog.


Leave a Reply

Your email address will not be published. Required fields are marked *