Programming in Swift · Challenge: Classes vs. Structures | Ray Wenderlich


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/5994-programming-in-swift/lessons/49

Hey. quick question. Jessy used a for loop to replace the map method of the array. When I did the challenge I opted to switch the code to look like this:

students.map { student in student.grade += curveAmount }
students.sort { $0.grade > $1.grade }

My question, is there a particular reason why the for loop is a better choice here?

@jessycatterwaul Can you please help with this when you get a chance? Thank you - much appreciated! :]

map is not intended to “replace a for loop”. That is, map is intended to return a transformed sequence, not mutate a sequence. Swift doesn’t enforce that, though, so you can use map here; it’s just not the clearest option.

forEach is better. It doesn’t return a value:

students.forEach { student in student.grade += curveAmount }

I opted to use a for loop instead of forEach, but they’re both valid!

Thank you. My programming knowledge is pretty out of date and methods like map are new to me. More specifically, being able to modify the functionality of a method with a closure blew my mind a couple days ago and I needed to do some extra curricular research to really grasp the concept! :joy:

That said, my first inclination would have been a for loop, but I try and think “now what would the Catterwauls do?”. You and Catie often surprise me with the nifty tricks that we can use with Swift.

1 Like