Why is Swift String Manipulation like that
Warning
String manipulation is notoriously tricky in Swift. Some common complaints
- Three different types, String, Substring, and Character.
- Cannot iterate a String with Integer. You need a separate datatype called
String.Index.
So a simple palindrome search goes from this in Python:
To this in Swift:
See the perplexing syntax? There are several reasons, though.
-
Substrings. Strings are value types, copied on assignment or when passed to a function. This can be good for stability but bad for efficiency, especially on large strings. Substring does not create a new instance.
-
String.Index, Character. Swift strings are Unicode-correct, which means they can handle complex characters and emoji. Some emoji are 3-4 characters combined in length. Words with "extended grapheme clusters" like "é", "김" and "🇮🇳" will vary in length as integers, but in String.Index they are all length 1. Apple's example
It's always a compromise, one or the other.
The difference between ordinary and extraordinary is that little extra.
- Jimmy Johnson (1943--)