NSRange: Crash when using index with strings containing special characters

I try to build a range in a string containing german umlauts (e. g. ä,ö,ü).

import Foundation

let testString = NSString("Wä") as String
let range = NSRange(testString.startIndex..<testString.endIndex, in: "Wäsche")

This example crashes with a fatal error with no further information printed on the console. My debugger halts with
EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

When I replace the umlauts with regular ascii characters, it works:
let range = NSRange(testString.startIndex..<testString.endIndex, in: "Wasche")
It also works when I don't use NSString.

The crash first occurred after updating to the new Xcode version.
Xcode 10.2
Build version 10E125

I'm not sure if I made a mistake here or it's a bug. Maybe this has something to do with the change in string encodings?

You're using indexes from one string on another string. Indexes valid in one string don't have to be valid in a different string (and collections in general)
If you use the same string there is no error

let testString = NSString("Wä") as String
let range = NSRange(testString.startIndex..<testString.endIndex, in: testString)
3 Likes
Terms of Service

Privacy Policy

Cookie Policy