The specificity of String
has mostly been addressed in other answers. To paraphrase: String
has a specific Index
which is not of type Int
because string elements do not have the same size in the general case. Hence, String
does not conform to RandomAccessCollection
and accessing a specific index implies the traversal of the collection, which is not an O(1) operation.
Many answers have proposed workarounds for using ranges, but they can lead to inefficient code as they use String methods (index(from:)
, index(:offsetBy:)
, ...) that are not O(1).
To access string elements like in an array you should use an Array
:
let array = Array("Hello, world!")
let letter = array[5]
This is a trade-off, the array creation is an O(n) operation but array accesses are then O(1). You can convert back to a String when you want with String(array)
.