Why does Swift not let you access a string’s index directly?

Have you ever tried to access an index on a Swift string directly? In Swift, using foo[2] will result in the error: subscript is not available. This is because subscripting is only defined for String.index as follows: subscript(Range<String .Index>).

Swift implements it this way so that it is safe with all unicode strings, however it makes the call site ugly if you don’t care about unicode correctness. You have to use Index like foo[index(foo.startIndex, offsetBy: index)].

This can be easily avoided by adding this small extension to String

extension String {
  subscript (i: Int) -> String {
    return String(self[index(startIndex, offsetBy: i)])

Perfect! Now, we can access individual characters like:

var char = foo[3]