Skip to content

Swift/StringUTF16View.swift:368: Fatal error: String index is out of bounds. #82359

Open
@Prakash7247

Description

@Prakash7247

Description

Using a SwiftUI TextField with the selection property causes a crash when I type numbers, move the cursor to the middle, and continue typing. The error is: String index is out of bounds

Reproduction

struct ios18: View {
    @State var goal: Int = 0
    @State private var goalString: String = ""
    private let numberFormatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.usesGroupingSeparator = true
        return formatter
    }()
    @State private var selection: TextSelection? = nil
    
    var body: some View {
        TextField("Enter something", text: $goalString, selection: $selection)
            .keyboardType(.decimalPad)
            .onChange(of: goalString) { _ in
                goalString = goalString.filter { $0.isNumber }
                goal = Int(goalString) ?? 0
                goalString = numberFormatter.string(for: goal) ?? "0"
            }
        
    }
}

Stack dump

struct ios18: View {
    @State var goal: Int = 0
    @State private var goalString: String = ""
    private let numberFormatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.usesGroupingSeparator = true
        return formatter
    }()
    @State private var selection: TextSelection? = nil
    
    var body: some View {
        TextField("Enter something", text: $goalString, selection: $selection)
            .keyboardType(.decimalPad)
            .onChange(of: goalString) { _ in
                goalString = goalString.filter { $0.isNumber }
                goal = Int(goalString) ?? 0
                goalString = numberFormatter.string(for: goal) ?? "0"
            }
        
    }
}

Expected behavior

Not getting crash.

Environment

On debug environment

Additional information

Simulator.Screen.Recording.-.iPhone.16.-.2025-06-19.at.12.17.20.mp4

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.crashBug: A crash, i.e., an abnormal termination of softwaretriage neededThis issue needs more specific labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions