Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String.Index to Int or Range<String.Index> to NSRange

Tags:

string

swift

So I've found issues relating to the case of converting NSRange to Range<String.Index>, but I've actually run into the opposite problem.

Quite simply, I have a String and a Range<String.Index> and need to convert the latter into an NSRange for use with an older function.

So far my only workaround has been to grab a substring instead like so:

func foo(theString: String, inRange: Range<String.Index>?) -> Bool {
    let theSubString = (nil == inRange) ? theString : theString.substringWithRange(inRange!)
    return olderFunction(theSubString, NSMakeRange(0, countElements(theSubString)))
}

This works of course, but it isn't very pretty, I'd much rather avoid having to grab a sub-string and just use the range itself somehow, is this possible?

like image 946
Haravikk Avatar asked Jan 24 '15 18:01

Haravikk


People also ask

What is Nsrange in Swift?

A structure used to describe a portion of a series, such as characters in a string or objects in an array.

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.


2 Answers

let index: Int = string.startIndex.distanceTo(range.startIndex)
like image 142
Alexander Volkov Avatar answered Nov 07 '22 04:11

Alexander Volkov


I don't know which version introduced it, but in Swift 4.2 you can easily convert between the two.

To convert Range<String.Index> to NSRange:

let range   = s[s.startIndex..<s.endIndex]
let nsRange = NSRange(range, in: s)

To convert NSRange to Range<String.Index>:

let nsRange = NSMakeRange(0, 4)
let range   = Range(nsRange, in: s)

Keep in mind that NSRange is UTF-16 based, while Range<String.Index> is Character based. Hence you can't just use counts and positions to convert between the two!

like image 28
hnh Avatar answered Nov 07 '22 03:11

hnh