Very often I find myself trying to access a character in string using a given index, however due to the way strings are implemented in Swift, it’s not that easy.
Ideally, given a string, I’d like to access a character at index 3 like this:
let input = "Swift Tutorials"
let char = input[3]
Unfortunately, this won’t work and the compiler will throw the following error:
‘subscript(_:)’ is unavailable: cannot subscript String with an Int, use a String.Index instead.
The correct way of getting a character at index 3 involves using String.Index:
let input = "Swift Tutorials"
let char = input[input.index(input.startIndex, offsetBy: 3)]
Using the above method everywhere in your project would end up cluttering your code. By creating an extension to the StringProtocol and implementing the subscript method, we can bring this functionality into every String (and Substring) in Swift.
Here is the full code of the extension:
extension StringProtocol {
subscript(offset: Int) -> Character {
self[index(startIndex, offsetBy: offset)]
}
}
Which can be used just like we originally wanted to:
let input = "Swift Tutorials"
let char = input[3]
If you’d like to convert the character back to string, cast it like that:
let char = String(input[3])
Related tutorials:
- How to convert String to Double or Float in Swift
- Floating point precision in Swift String
- How to pick a random element from an array in Swift
- How to use switch statement with enum in Swift
Check out Apple’s official documentation of String.