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.