When using ForEach, i get an error when I type ForEach(0...100) instead of ForEach(0..<101). What is the reasoning behind this?
You probably understand that Int
is not the same type as Double
, and even though they are both numbers, you can't use them interchangably. A function that takes an Int
as a parameter will not accept a Double
instead.
The same is true with a Range
and a ClosedRange
. They are two different types that can not be used interchangably. The ForEach
initializer that you are calling is set up to take a Range
as a parameter, and not a ClosedRange
. So, that is the basic reason why you are getting the error.
I can't really remember the reasoning behind why the ForEach
initializer is set up that way, but I think that somebody has explained it to me in these forums before, some years ago maybe. Perhaps somebody else can provide further insight here.
In the WeSplit app, I am having a hard time understanding why do we need to add 2 to numberOfPeople when we calculate peopleCount. Paul has talked about how the picker shows 4 but I do not understand the thinking behind.
The reason we add 2 to the number of people when calculating the total is becuase the picker basically has an array of options with indeces 0...98
but each of those options is showing a label with a value 2...100
. Since we bound the numberOfPeople
property to the picker, it will automatically assume that we want to set the value of numberOfPeople
to whatever index was selected, rather than the value shown in the label. So, when we select "2 People" it is actually setting numberOfPeople
to zero.
You can get around this default behavior of the picker by using the .tag()
modifier to specify a value that you would like to use instead of the indeces. But, I assume that since this is your first project, Paul probably didn't want to make things more complicated than they needed to be and risk confusing you further by explaining the .tag()
modifier.
If you want to try using the .tag()
modifier, you can set up your picker like this...
Picker("Number of People", selection: $numberOfPeople) {
ForEach(2..<101) {
Text("\($0) people").tag($0)
}
}
Then, it will set numberOfPeople
to the same number that is being used in the labels of your picker, rather than the indeces. That way, you shouldn't have to add 2 to the numberOfPeople when calculating the total.
First question of the WeSplit review, option 1 states that SwiftUI allows no more than 10 child views inside each parent. we are then told that if we want to add more, we should place the views inside groups. Are groups here Section?
Yes, a Section
is basically the same as a Goup
except that a Section
is meant to be used inside of a Form
and will try to format its contents to look a little bit nicer inside of the Form
.