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

Days 16 & 17 WeSplit: 2...99 vs 2..<100

Forums > 100 Days of SwiftUI

When setting the range of values for the number of people splitting the tip (...restaurants must have reeeally lengthly tables nowadays), the compiler doesn't accept 2...99 to represent the possibilities 2 through 99, inclusive.

                    Picker("Number of people", selection: $numberOfPeople) {
                        ForEach(2 ... 99) {
                            Text("\($0) people")
                        }
                    }

Only the 'open' range 2..<100 works for representing 2 through 99, inclusive.

                    Picker("Number of people", selection: $numberOfPeople) {
                        ForEach(2 ..< 100) {
                            Text("\($0) people")
                        }
                    }

According to the error that appears, the application's expecting a Range\<Int> item rather than a ClosedRange\<Int> one, which I'm guessing is a requirement of ForEach.

Does anyone know why ForEach accepts a(n open) range but not a closed one?

2      

I imagine it's because code like this is probably pretty common:

ForEach(0..<items.count) { item in
    //blah blah blah
}

Note that this works:

ForEach(2...99, id: \.self) {
    Text("\($0) people")
}

Although it is a little different than how 2..<100 works.

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!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.