Dauris Little
all
  • About
  • Dauris’s Portfolio
  • Blogging Lyf
  • Contact
© 2016 Dauris Little. All rights reserved.
  • Home
  • Blog
  • blog
  • Using forEach, forEnumerated, forIn within Swift
November 16, 2025

BLOG & Gossip

Avatar photo
Dauris
Friday, 10 July 2020 / Published in blog, iOS, Programming Languages, Swift

Using forEach, forEnumerated, forIn within Swift

Swift provides us with multiple ways to loop through items in a collection, they are:

for pokemon in pokemons {
   print(pokemon)
}

pokemons.forEach { (pokemon) in
   print("Pokemon", pokemon)
}

for (index, element) in pokemons.enumerated() {
   print("Number:", index, "Pokemon:", element)
}

Using for in

many programming languages the for in loo is called for-each. Standard loop statement in other languages uses this format:

for (i = 0; i < n; i++) {
   ///some fancy collecion to loop thur
}

Please note: Swift 3 no longer supports c-style for-loops

Now when using swift this approach is a little different, the rationale of this for-in syntax is it can be used to loop over ranges, iterators, strings, sequences, and collections with the same syntax.

let pokemons = ["Pikachu", "Charmander", "Squirtle", "Bulbasaur"]

for i in 0...< pokemons.count {
   print("Pokemon \(i+1):" pokemons[i])
}

//output:
Pokemon 1: Pikachu
Pokemon 2: Charmander
Pokemon 3: Squirtle
Pokemon 4: Bulbasaur

Within Swift the use of object types like arrays, dictionaries, and sets are known as collection. Any collection can be iterated with a for-in loop. For example with dictionary:

let pokedex = ["Electric":"Pikachu","Water":"Squirtle","Fire":"Charmander","Grass":"Bulbasaur"]

for (type, pokemon) in pokedex {
   print("The \(type)'s Pokemon is \(pokemon))
}

//output
The Electric's Pokemon is Pikachu
The Water's Pokemon is Squirtle
The Fire's Pokemon is Charmander
The Grass's Pokemon is Bulbasaur

In addition, Swift also  provided two range operators lowerBound...upperBound as a shortcut for expressing a range of values.

Take note: lowebound is greater than upperBound the code will crash

for i in 0...5 {
   print(i)
}
//output
0
1
2
3
4
5

for i in 0..<5 {
   print(i)
}

//output
0
1
2
3
4

If interested in reversing the range while looping, we can easily achieve that using  reversed

for i in (0...5).reversed() {
   print(i)
}

//output
5
4
3
2
1
0

Stride

As I referenced before, C-Style for loops are no longer supported within Swift 3, so you’re probably asking how to acquire the ‘increment of the counter’ (i++). We accomplished this by using stride, and this helps us to move from one value to another using any incremental value, we can also specify whether the upperBound is inclusive or exclusive.

for i in stride(from 0, to: 10, by: 2) {
   print(i)
}

//output
0
2
4
6
8

Using for each

pokemons.forEach {
   print("Pokemon", pokemon)
}

//output
Pokemon Mewtwo
Pokemon Snorlax
Pokemon Eevee

Swift provides a dedicated method forEach for specific, unlike the above forIn this method can’t break the loop partway (at some point). It has to loop over each item in the sequence. It has to loop over each item in the sequence. This helps people reading your code to figure out your intent: that you want to act on all items, and won’t stop in the middle.

Please note: break stops execution in a loop immediately and continues directly after the loop.

continue only exits the current iteration of the loop — it will jump back to the top of the loop and resumes up from there for next iteration

var oddNumbers = [Int]()

for numbers in (0...100) {
   guard oddNumbers.count < 15 else {
      break
   }

   guard numbers % 3 == 0 else {
      continue
   }
   
   oddNumbers.append(numbers)

   print(oddNumbers)
}

the same cannot be achieved in forEach with break and continue, so we need something like:

let oddNumbers = (0...100).filter {numbers -> Bool in
   return numbers % 3 == 0
}.prefix(10)

print(oddNumbers)

Using for enumerated

This Swift loop iterates to each of the items by also telling the index of it. In case if we need to iterate the elements and need their index also, then forEnumerated is the perfect loop for us.

Nested for loops:

var pokedex = ["001", "002", "003"]
var pokemons = ["Bulbasaur", "Ivysaur", "Venusaur"]

for i in 0..< pokedex.count {
   var string = "\(pokedex[i]) is "

   for _ in 1...3 {
      string += "\(pokemons[i])"
   }

   print(string)
}

//output
001 is Bulbasaur
002 is Ivysaur
003 is Venusaur

While:

// a while loop performs a set of statements until a condition becomes false
while condition {
   //statements
}

var index = 0 
while index < pokemons.count {
   print(pokemon[index])
   index += 1
}

//output
Bulbasaur
Ivysaur
Venusaur

Repeat:

//repeat while loop is similar to do while loops in other languages

repeat {
   statements
} while condition

var index = 0
repeat {
   print (pokemons[index])
   index += 1
} while index < pokemons.count 

//output
Bulbasaur
Ivysaur
Venusaur

It is similar to the above while loop but the major difference is that this loop evaluates the condition after running the statements. Either way, both while and repeat are best used in the loops where the numbers of steps are unknown.

  • Tweet
Tagged under: developer knowledge, iOS, programming w/ swift, swift, swift 5

What you can read next

Java vs Kotlin
Java Or Kotlin Language: Deciding Which Option to Use for Android Development
Using WooCommerce in 2021
QR Reader in Android w/ Kotlin

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Categories

Recent Posts

  • Gesture Controls for Android w/Kotlin

    Incorporating Gesture controls in your android ...
  • Android Rating: In-App Review API

    An app rating and reviews are crucial if you wa...
  • QR Reader in Android w/ Kotlin

    Turn your phone's camera into a QR scanner...
  • Creating Advance Custom Snackbar w/ Kotlin

    Ask 100 different developers about what they fi...
  • Swift Has Tuple

    Swift provides us with a type called Tuple whic...

Recent Comments

  • Homepage on Integrating Google’s reCAPTCHA w/Android
  • Cleora Weideman on Integrating Google’s reCAPTCHA w/Android
  • alpha femme keto Reviews on Integrating Google’s reCAPTCHA w/Android
  • best skin care products reviews on Integrating Google’s reCAPTCHA w/Android
  • Robyn on Integrating Google’s reCAPTCHA w/Android

Archives

  • January 2022
  • December 2021
  • September 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • February 2021
  • January 2021
  • December 2020
  • October 2020
  • August 2020
  • July 2020
  • May 2020
  • March 2020
  • February 2020
  • December 2019
  • October 2019
  • September 2019
  • May 2019
  • March 2019
  • February 2019
  • January 2019
  • August 2018
  • April 2018
  • August 2017
  • November 2016
  • August 2016

Categories

  • .NET & .NET Core
  • Active Directory
  • Android
  • API
  • bitcoin
  • blog
  • C#
  • Development
  • E-Commerce
  • HTML5
  • iOS
  • Java
  • Javascript
  • Kotlin
  • Language
  • Like I Am Five
  • Mobile Development
  • New Web Site
  • Programming Languages
  • Swift
  • Tutorial
  • Uncategorized
  • Web Application Development
  • Windows AD

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

© 2015. All rights reserved. Buy Kallyas Theme.

TOP
This site uses tracking cookies to personalize content and ads. AcceptLearn More