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 = ""
}
}