The Ultimate (FOR - LOOP) Swift



1. Standard (For - In Loop)
Such as items in an array, ranges of numbers, or characters in a string.
this example for - in loop

let items = [1, 2, 3, 4, 6, 7, 14]

for item in items {
   print(item)
}

print(items) // 1, 2, 3, 4, 6, 7, 14


2. Loop with key (For - In Loop)
same like a standard loop but this loop use key as index
and example :

var items = [1, 3, 10, 4, 6, 7, 14]

for (key, num) in items.enumerated() {
    items[key] = 1
}

print(items) //1, 1, 1, 1, 1, 1, 1


//if use outlet collection

@IBOutlet var menuMidButtons: [UIButton]!
// from
self.menuMidButtons[0].layer.cornerRadius = self.menuMidButtons[0].frame.size.height / 2
self.menuMidButtons[1].layer.cornerRadius = self.menuMidButtons[1].frame.size.height / 2
self.menuMidButtons[2].layer.cornerRadius = self.menuMidButtons[2].frame.size.height / 2

self.menuMidButtons[0].alignTextBelow()
self.menuMidButtons[1].alignTextBelow()
self.menuMidButtons[2].alignTextBelow()


// less code like this below

for (key, _) in menuMidButtons.enumerated() {
   menuMidButtons[key].layer.cornerRadius = self.menuMidButtons[key].frame.size.height / 2
   menuMidButtons[key].alignTextBelow()
}


3. Loop over range (For - In Loop)


Here’s that code example with the closed range operator

//ex: 1
for item in 1...5 {
   print(item) // 1, 2, 3, 4, 5

}


//ex: 2
for item in 0..<9 {
  print(items) // 0, 1, 2, 3, 4, 5, 6, 7, 8

}
//ex: 3 let items = [1, 3, 10, 4, 6, 7, 14] for item in 0..<items.count { print(item) // 0, 1, 2, 3, 4, 5, 6 }


4. Loop For Each

This loop same like standard for - in loop, and then check example below:

let items = [1, 2, 3, 4, 6, 7, 14]

items.forEach { item in
    print(item)
}


5. Loop with Zip (For - In Loop )

for example, both two array.  you can use zip loop

struct IsZipLoop {
    var isBool: Bool
    var isItem: Int
}
let items = [0, 1, 2, 3, 4, 5, 6]

let Bools = [true, false, false, false, false, false, false]

var list = [IsZipLoop]()

for (item, bool) in zip(items, Bools) {
    list.append(IsZipLoop(isBool: bool, isItem: item))
}



6.  Loop Key and Zip (for In Loop)

this loop use key and zip

import UIKit

class ViewController: UIViewController {
    let items = [1, 2, 3, 4, 6, 7, 14]
    let bools = [false, false, false, false, false, false, false]

    override func viewDidLoad() {
        super.viewDidLoad()
        
        for ((offset: key, element: item), bool) in zip(items.enumerated(), bools) {
            print(key, item, bool)
        }
        
    }
}

// result print in debug area

0 1 false
1 2 false
2 3 false
3 4 false
4 6 false
5 7 false
6 14 false

For the next post to be while - loop.

No comments: