0

After upgrade to Xcode Version 10.2 (10E125), progress Fatal error at range.upperBound.samePosition(in: utf16)

extension String {

    //Range => NSRange
    func nsRange(from range: Range<String.Index>) -> NSRange {
        guard let to = range.upperBound.samePosition(in: utf16) else {
            return NSMakeRange(0, 0)
        }

        guard let from = range.lowerBound.samePosition(in: utf16) else {
            return NSMakeRange(0, 0)
        }

        return NSMakeRange(utf16.distance(from: utf16.startIndex, to: from), utf16.distance(from: from, to: to))
    }

    //NSRange =>Range
    func range(from range: NSRange) -> Range<String.Index>? {
        guard let from16 = utf16.index(utf16.startIndex, offsetBy: range.location, limitedBy: utf16.endIndex) else { return nil }
        guard let to16 = utf16.index(from16, offsetBy: range.length, limitedBy: utf16.endIndex) else { return nil }
        guard let from = String.Index(from16, within: self) else { return nil }
        guard let to = String.Index(to16, within: self) else { return nil }
        return from ..< to
    }
}

it start crash in

range.upperBound.samePosition(in: utf16)

error

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

I expect good running

image: [1]: https://i.stack.imgur.com/bfbbf.png

Bhaumik
  • 1,218
  • 1
  • 11
  • 20
  • 1
    Where does `utf16` come from? – El Tomato Mar 28 '19 at 03:12
  • Possible duplicate of [How to convert Range to NSRange?](https://stackoverflow.com/questions/45493826/how-to-convert-rangestring-index-to-nsrange) – El Tomato Mar 28 '19 at 03:12
  • I use this code in extension of String, so utf16 possible is self.utf16, I did see there answer,it run good before Xcode 10.2, but After upgrade to Xcode Version 10.2 (10E125), progress Fatal error – PengZishang Mar 28 '19 at 03:28
  • 2
    But you don’t need any of your code, because string conversion between range and NSRange is now built in – matt Mar 28 '19 at 03:38
  • thanks a lot ,conversion between range and NSRange already built in after swift4 – PengZishang Mar 28 '19 at 04:26

0 Answers0