Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Int to String.CharacterView.Index

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..

like image 349
nekonari Avatar asked May 18 '16 16:05

nekonari


People also ask

Can you index a string in Swift?

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.

How can I convert the index of a string to an integer in Python?

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.

How do I convert a string to an int in C++?

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.


1 Answers

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.

like image 69
ZGski Avatar answered Sep 19 '22 16:09

ZGski