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..
To access certain parts of a string or to modify it, Swift provides the Swift. Index type which represents the position of each Character in a String. The above prefix(upTo:) method returns a Substring and not a String.
To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. Use the syntax print(int("STR")) to return the str as an int , or integer.
One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With