cho.sh
Why is Swift String Manipulation like that

Why is Swift String Manipulation like that

Warning

Over a year old. May be outdated

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:

python
if string[i] != string[length - 1 - i]:

To this in Swift:

swift
// ...
if String(string[String.Index(string.startIndex, offsetBy: i)]) != String(string[String.Index(string.endIndex, offsetBy: -i)]) // What is wrong with you?
// ...

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

    swift
    let cafe = "Cafe\u{301} du 🌍"
    print(cafe) // Prints "Café du 🌍"
    print(cafe.count) // Prints "9"
    print(Array(cafe)) // Prints ["C", "a", "f", "é", " ", "d", "u", " ", "🌍"]

It's always a compromise, one or the other.

The difference between ordinary and extraordinary is that little extra.

  • Jimmy Johnson (1943--)
Backlinks3