Skip to content

Instantly share code, notes, and snippets.

@gallaugher
Last active June 27, 2018 01:43
Show Gist options
  • Select an option

  • Save gallaugher/8c3ecd051c584dad1839b25a44e0ddcb to your computer and use it in GitHub Desktop.

Select an option

Save gallaugher/8c3ecd051c584dad1839b25a44e0ddcb to your computer and use it in GitHub Desktop.
for in vs. .map
// the code below uses a for in loop to create a new array named scoreAfterBonus where every element in scores gets a 10% bonus
var scoresAfterBonus: [Double] = []
for score in scores {
scoresAfterBonus.append(Double(score) * 1.1)
}
// the code below uses the .map method to do the same thing with just one line. Also note that the array scoresAfterBonus can even be created as a constant if it’s not going to change in the future. Note another array tenPerentScores is created below to demonstrate that it can be created as a constant with let, impossible in the for loop which needs to change the array with each iterration using .append
let tenPercentScores = scores.map { Double($0) * 1.1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment