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?
A structure used to describe a portion of a series, such as characters in a string or objects in an array.
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.
let index: Int = string.startIndex.distanceTo(range.startIndex)
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!
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