Hello,
I'm trying to find the sum of a user-generated array by using the following code.
The above code doesn't work because, for some reason, it can't find 'pointsReceived' in scope.
I have this structure on the top of the page with the following data format:
I'm trying to add all the points received (there can be multiple rows of this data). How should I do that?
Thank you!
I'm trying to find the sum of a user-generated array by using the following code.
Code Block let total = pointsReceived.reduce(0, +)
The above code doesn't work because, for some reason, it can't find 'pointsReceived' in scope.
I have this structure on the top of the page with the following data format:
Code Block struct Grade: Hashable, Identifiable { var id = UUID() var assessmentName: String! var pointsReceived: Double! var pointsPossible: Double! }
I'm trying to add all the points received (there can be multiple rows of this data). How should I do that?
Thank you!
I'm trying to find the sum of a user-generated array by using the following code.
Where is the array? To apply reduce, the thing applied needs to be an Array. (Or at least a Sequence.)I have this structure on the top of the page with the following data format:
In your shown code, there aren't any Arrays.
Assuming you have an Array of Grade,
Code Block var grades: [Grade] = [/*...*/]
you can write something like this:
Code Block let total = grades.reduce(0, {$0 + $1.pointsReceived})
By the way, why are you using Implicitly Unwrapped Optionals in your struct?
If you know the property can be nil, you should use normal Optionals:
Code Block struct Grade: Hashable, Identifiable { var id = UUID() var assessmentName: String? var pointsReceived: Double? var pointsPossible: Double? }
(In this case, you need to update the code to reduce.)
Or else, if the property cannot be nil, you should better use non-Optional:
Code Block struct Grade: Hashable, Identifiable { var id = UUID() var assessmentName: String var pointsReceived: Double var pointsPossible: Double }