Question about String.Index

Hello,

I wrote a code to get second character of the string as follows:




print("name:")

let name = readLine()!



print("Age:")

let age = Int(readLine()!)!



print("Name:\(name), Age:\(age)")



let idx = name.index(name.startIndex, offsetBy: 1)

print(name[idx])

print(idx)

I entered these to test this code;

name: John

age:20

I expected result: name:John

age:20 o

1

but I got:

name:John

age:20

o

Index(_rawBits: 65799)//I expected 1

If someone can explain why I can't get index number of the string, I'd be very appreciated.

thanks for your answer in advance.

c00012

Index is not an Int.

You need to get the Int position from the index, for instance with this:

let index: Int = name.distance(from: name.startIndex, to: idx)
print(index)

But in your case, you have offset by 1 from start, that is the Int you look for.

Question about String.Index
 
 
Q