NSNumber conversion in Textfield crashes

218 Views Asked by At

I went through old questions but couldn't find a solution for this:

I have this simple View:

struct ContentView: View {
    
    @State var myInt: Int = 0
    
    var body: some View {
        TextField("Int", value: $myInt, formatter: NumberFormatter())
    }
}

In runtime, entering '1111111111111111111', or any 20 digits or more into the TextField crashes with:

"Fatal error: Unable to bridge NSNumber to Int: file"

If I change the type to:

@State var myInt: NSNumber = 0

the entered value is converted to '111111111111111110000' and it's not crashing.

My problem is, I want myInt to be of type Int, not NSNumber, while staying safe from crashing.

I made several attempts to convert String to NSNumber to Int but nothing worked.

Attempt 1: Using a Binding, validating in the setter

var body: some View {
        TextField("Int", value: Binding(
            get: { myInt },
            set: {
                var fixedInt: Int
                if $0 > 9223372036854775807 { fixedInt = 0 } else { fixedInt = $0 }
                myInt = fixedInt }
        ), formatter: NumberFormatter())
    }
}

Unfortunately, the problem persists.

1

There are 1 best solutions below

0
soundflix On

Thanks to the comments and which led me to focussing better on my question, I found a solution.

First, I finally understood how to access NumberFormatter properties. It wasn't clear to me. I can set them in init():

struct ContentView: View {
    
    @State var myInt: Int = 0
    
    let formatter = NumberFormatter()
    
    init() {
        formatter.maximum = 9223372036854775807
    }
    
    var body: some View {
        TextField("Int", value: $myInt, formatter: formatter)
    }
}

To my surprise, it is still possible to crash with giving the values 9223372036854775808 and 9223372036854775809. It is not entirely satisfactory in theory, but practically, the values my app will be using are lower, so I can set:

formatter.maximum = 922337203685477580

or less, of course.