'Crash when init a Range from NSRange

I got a crash report on Crashlytics with this following exception.

Fatal Exception: NSInvalidArgumentException
-[__NSCFString characterAtIndex:]: Range or index out of bounds

The stack trace is:

Fatal Exception: NSInvalidArgumentException
0  CoreFoundation                 0x990fc __exceptionPreprocess
1  libobjc.A.dylib                0x15d64 objc_exception_throw
2  CoreFoundation                 0x1a2564 -[__NSCFString characterAtIndex:].cold.1
3  CoreFoundation                 0x1a2598 -[__NSCFString getCharacters:range:].cold.1
4  CoreFoundation                 0x2498c -[__NSCFString characterAtIndex:]
5  libswiftCore.dylib             0x218738 _StringGuts.foreignScalarAlign(_:)
6  libswiftCore.dylib             0x200e20 _StringGuts.isOnUnicodeScalarBoundary(_:)
7  libswiftCore.dylib             0x1ff76c _StringGuts.isOnGraphemeClusterBoundary(_:)
8  libswiftCore.dylib             0x1ff580 String.Index.init<A>(_:_genericWithin:)
9  libswiftCore.dylib             0x1ff81c String.Index.init<A>(_:within:)
10 libswiftFoundation.dylib       0x35484 Range<>.init(_:in:)

This is the code where the crash is reported at the if let statement.

if let swiftRange = Range(range, in: string) {
    string = string.replacingCharacters(in: swiftRange, with: replacement)
}

I did some experiments in Playground and found that when the location or the length of the NSRange variable exceed the string, the init method doesn't crash but returns a nil value and hence no crash. It crashes when either location or length is negative then it would raise a Precondition failed instead of exception.

Any leads would be appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source