Swift : Difference between Instance methods forEach & forIn Loop

Rahul Dubey
Aug 26, 2017 · 2 min read

Swift 3 provides a new way to iterate a for loop using ForEach. It works in similar way as for in loop does but there are some basic differences between the two.

I tried running both the instance method in a function on a Employee Object. Below is the snapshot of the playground.

If you see by above example there is absolutely no difference between the two if you are trying to access and iterate through each element of the array.

Difference 1 : You cannot use break or continue statement to exit the current call of the closure in forEach loop, but you can do the same in forIn loop.

Attached snapshot below:

Difference 2: Using return statement ForEach loop exits only for the current call in the closure while ForIn loop exits all the next subsequent calls as well.

Attached snapshot below:

You can download the playground snipped from my GitHub repository https://github.com/creative-rd/SwiftNuggets/tree/master/Swift_ForEachvsForIn.playground

Stay Calm, Code On !

Reference: https://developer.apple.com/documentation/swift/array/1689783-foreach

)

Rahul Dubey

Written by

Software Engineer | SAFe® 4 Practitioner

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade