Khwaja Moiz Khwaja Moiz - 4 years ago 136
iOS Question

Cannot find char at position and index of char of a string var in Swift 2

Equivalent functions in Swift 2 of Java's charAt() and indexOf() ?

Answer Source

Did you read the NSString documentation? String and NSString are not identical, but as mentioned by this answer most functions are more or less the same. Anyway, the two exact functions you ask for are right there:

Java's charAt:

func characterAtIndex(_ index: Int) -> unichar

Java's indexOf:

func rangeOfString(_ searchString: String) -> NSRange

The NSRange data type contains just 2 variables: location and length that tell you where the substring is in the original string and how long it is. See the documentation.

//Java
"abc".indexOf("b") => 1
//Swift
"abc".rangeOfString("b").location #=> 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download