Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

Application crashes when using TextEditor(text, selection)

I have a TextEditor, to the constructor of which in addition to the text I pass an object of the TextSelection? type. I check on the Simulator with iOS 18.2. An attempt to clear the text leads to a crash with the message "Thread 1: Fatal error: String index is out of bounds" in Xcode.

More about the error:

libswiftCore.dylib`_swift_runtime_on_report:
-> 0x194f32024 <+0>: ret

More about the reproduction conditions:

struct MyView: View {

    @Bindable private var viewModel = MyViewModel()
    @State var myTextSelection: TextSelection? = nil

    var body: some View {
        ZStack {
            // Some other code
            myEditor
            // Some other code
        }
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button {
                    viewModel.clear()
                } label: {
                    Label("Clear", systemImage: "eraser")
                }
            }
         }
    }

    var myEditor: some View {
        ZStack(alignment: .topLeading) {
            TextEditor(text: $viewModel.text, selection: $myTextSelection)
                .disableAutocorrection(true)
                .autocapitalization(.sentences)
        }
        // Some other code
    }
}

MyViewModel:

@Observable
final class MyViewModel: ObservableObject {

    var text: String = ""

    func clear() {
        text = ""
    }
}

Similar experience on macOS.

Using TextSelection with a TextEditor is very unstable and crashes quite easily, especially if the selection is used to mutate the string bound to the TextEditor. (Which is common for operations that involve replacing the selected text.)

In Xcode, the following error is reporting in the console:

Swift/StringUTF16View.swift:372: Fatal error: String index is out of bounds

The full call stack is pasted below

For any SwiftUI developers reading this:

Unscientifically, it feels like this happens much more frequently in an AppKit application hosting a TextEditor than it does inside a SwiftUI application.

If I make a demo SwiftUI app with nothing more than a ContentView and a TextEditor, then it's harder to trigger this bug (but not impossible, as I just did it). On the other hand, when used inside a much larger AppKit app, it happens quite easily even though the actual SwiftUI code isn't that different. 🤷‍♂️

Xcode Version 16.3 (16E140), macOS 15.4.1 (24E263)

Application crashes when using TextEditor(text, selection)
 
 
Q