Skip to content

Commit 5e6af4b

Browse files
committed
NSRange: fix init from RangeExpression in String
Prior to Swift 5, String uses UTF-16 for its Index and encodedOffset. However, this assumption is no longer valid and encodedOffset might be in UTF-8 for native contents in Swift 5. This change should make the initializer work as expected under either circumstances.
1 parent abc9ac7 commit 5e6af4b

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

Foundation/NSRange.swift

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -260,9 +260,10 @@ extension NSRange {
260260
public init<R: RangeExpression, S: StringProtocol>(_ region: R, in target: S)
261261
where R.Bound == S.Index {
262262
let r = region.relative(to: target)
263+
let u = target.utf16
263264
self = NSRange(
264-
location: r.lowerBound.encodedOffset - target.startIndex.encodedOffset,
265-
length: r.upperBound.encodedOffset - r.lowerBound.encodedOffset
265+
location: u.distance(from: target.startIndex, to: r.lowerBound),
266+
length: u.distance(from: r.lowerBound, to: r.upperBound)
266267
)
267268
}
268269

0 commit comments

Comments
 (0)