WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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?

1      

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.

1      

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

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.