I have enjoyed every bit of my journey in learning Swift 4. The language is incredibly intuitive, concise, and down right fun to work with at times. But today I came across String Indexing in Apple’s documentation. And I have to say… it isn’t all that intuitive.

The reason is because of the way Swift stores Characters in memory. Different characters can take up different amounts of memory. Therefore, Strings cannot be indexed by an Integer; and they must be iterated over to access a particular Character. Instead they are indexed by something called a String Index. This makes for some odd bits of code when you want to access a particular Character within a String.

For example. Given the String domain.

let domain = "https://ingax.com"

Access the first Character.

let firstChar: Character = domain[domain.startIndex]

Access the second Character.

let secondChar: Character = domain[domain.index(after: domain.startIndex)]

Access the third Character.

let thirdChar: Character = domain[domain.index(domain.startIndex, offsetBy: 2)]

The longhand form of accessing the fourth Character.

var fourthChar: Character = " "
var i = 1
for char in domain {
    fourthChar = char
    if(i == 4) {break} else {i += 1}

As you can see, the code isn’t so pretty. I wish I could just do this:

let fifthChar: Character = domain[4]

Leave a Reply