UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

ClosedRanged<Int> of range (-Int.max...Int.max-1) for Stepper View Crashes App

Forums > SwiftUI

struct ContentView: View {
    @State private var quantity = -Int.max
    var body: some View {
        Form {
            Stepper("\(quantity)", value: $quantity, in: -Int.max...Int.max-1)
        }
    }
}

As stated above, this range crashes the app. However, to my knowledge it should be able to handle the range (-Int.max...Int.max-1).

I would very much appreciate the explanation behind this occurrence.

Thank you.

2      

@nowroz found an interesting error!

However, to my knowledge it should be able to handle the range (-Int.max...Int.max-1).

Here's a test case. The Stepper works with a range of Int32 values. You can create a range with full Int values, but it crashes the app as you demonstrated.

However, if you substitute Int64 in the code below, you receive a different error. The error states:

Distance is not representable in Int

This isn't documented as far as I can tell.

struct LargeRangeTestView: View {
    // Change Int32 to Int64 yields this error:
    // --> Distance is not representable in Int

    @State private var stepperValue:Int32  = 0
    var startRange                         = Int32.min
    var endRange                           = Int32.max
    var veryLargeRange: ClosedRange<Int32> {startRange...endRange}

    // Can we make a Closed Range with a full Int?
    // This line does not crash the app.
    // But cannot be included in a Stepper.
    var hugeRange: ClosedRange<Int> { Int.min...Int.max }

    var body: some View {
        VStack {
            Text("Large Range Test").font(.largeTitle)
            HStack{
                Text("Min: \(startRange)")
                Text("Max: \(endRange)")
            }.font(.caption)
            Text("Value: \(stepperValue)").font(.title).padding(.vertical)
            Stepper(value: $stepperValue, in: veryLargeRange) {
                Text("Large Range")
            }
            Spacer()
        }.padding(.horizontal)
         .onAppear{ stepperValue = startRange }
    }
}

2      

@Obelix

Yes, I've noticed the different error when I explicitly typed Int64 just to be sure.

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.