How to convert Int to String.CharacterView.Index

nekonari picture nekonari · May 18, 2016 · Viewed 15k times · Source

This is driving me nuts.

In Swift 2.2, it makes it impossible to subscript String with Int. For example:

let myString = "Test string"
let index = 0
let firstCharacter = myString[index]

This will result with a compile error, saying

'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion

One workaround I see is to convert integer to the index type, but I can't figure out how..

Answer

ZGski picture ZGski · May 18, 2016

It's not that subscripting is impossible necessarily, it just takes one extra step to get the same results as before. Below, I've done the same thing as you, but in Swift 2.2

let myString = "Test string"
let intForIndex = 0
let index = myString.startIndex.advancedBy(intForIndex)
let firstCharacter = myString[index]

Swift 3.x + 4.x

let myString = "Test string"
let intForIndex = 0
let index = myString.index(myString.startIndex, offsetBy: intForIndex)
let firstCharacter = myString[index]

EDIT 1:

Updated code so you can use the Int that was passed into the "index" value elsewhere.


Syntax Edits:

I'll consistently update this answer to support the newest version of Swift.