Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have an array of Room objects. Each Room contains an array of Student objects.

So I want to get the sum of the number of students in all rooms.

So what I'm doing is :

self.rooms().map({ numberOfImagesToDownload += $0.students.count })

Is there another modern/intuitive way to do it or that's good ? Because map returns an array that is not used..

share|improve this question
4  
I don't think this is necessarily off-topic, but I also don't think it's all that great of a question for CodeReview. There's not really that much code to review. You don't really mention what, if anything, you think is particularly wrong with this, and you don't mention this being particularly slow or anything. I think it looks fine and you've given no context. CodeReview questions work better with quite a lot more code to look at. –  nhgrif Mar 12 at 10:44

1 Answer 1

map() does indeed create an array which in your case is discarded. It may be that the Swift compiler is smart enough to avoid the actual construction of the unused array (I don't know).

But using map() simply for the side effect is not necessary because there is a Swift function exactly suited for your purpose:

/// Return the result of repeatedly calling `combine` with an
/// accumulated value initialized to `initial` and each element of
/// `sequence`, in turn.
func reduce<S : SequenceType, U>(sequence: S, initial: U, combine: (U, S.Generator.Element) -> U) -> U

In your case:

let totalNumberOfStudents = reduce(self.rooms(), 0) { $0 + $1.students.count }

which has the additional advantage that the result can be assigned to a constant instead of a variable.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.