Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 644 Vote(s) - 3.53 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to iterate a loop with index and element in Swift

#11
Xcode 8 and Swift 3:
Array can be enumerated using `tempArray.enumerated()`

Example:

var someStrs = [String]()

someStrs.append("Apple")
someStrs.append("Amazon")
someStrs += ["Google"]


for (index, item) in someStrs.enumerated()
{
print("Value at index = \(index) is \(item)").
}

console:

Value at index = 0 is Apple
Value at index = 1 is Amazon
Value at index = 2 is Google
Reply

#12
For what you are wanting to do, you should use the `enumerated()` method on your **Array**:

for (index, element) in list.enumerated() {
print("\(index) - \(element)")
}
Reply

#13
Swift 5 provides a method called [`enumerated()`][1] for `Array`. `enumerated()` has the following declaration:

func enumerated() -> EnumeratedSequence<Array<Element>>

>Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.

---

In the simplest cases, you may use `enumerated()` with a for loop. For example:

let list = ["Car", "Bike", "Plane", "Boat"]
for (index, element) in list.enumerated() {
print(index, ":", element)
}

/*
prints:
0 : Car
1 : Bike
2 : Plane
3 : Boat
*/

---

Note however that you're not limited to use `enumerated()` with a for loop. In fact, if you plan to use `enumerated()` with a for loop for something similar to the following code, you're doing it wrong:

let list = [Int](1...5)
var arrayOfTuples = [(Int, Int)]()

for (index, element) in list.enumerated() {
arrayOfTuples += [(index, element)]
}

print(arrayOfTuples) // prints [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]


A swiftier way to do this is:

let list = [Int](1...5)
let arrayOfTuples = Array(list.enumerated())
print(arrayOfTuples) // prints [(offset: 0, element: 1), (offset: 1, element: 2), (offset: 2, element: 3), (offset: 3, element: 4), (offset: 4, element: 5)]

---

As an alternative, you may also use `enumerated()` with `map`:

let list = [Int](1...5)
let arrayOfDictionaries = list.enumerated().map { (a, b) in return [a : b] }
print(arrayOfDictionaries) // prints [[0: 1], [1: 2], [2: 3], [3: 4], [4: 5]]

---

Moreover, although it has some [limitations][3], `forEach` can be a good replacement to a for loop:

let list = [Int](1...5)
list.reversed().enumerated().forEach { print($0, ":", $1) }

/*
prints:
0 : 5
1 : 4
2 : 3
3 : 2
4 : 1
*/

---

By using `enumerated()` and `makeIterator()`, you can even iterate manually on your `Array`. For example:

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

var generator = ["Car", "Bike", "Plane", "Boat"].enumerated().makeIterator()

override func viewDidLoad() {
super.viewDidLoad()

let button = UIButton(type: .system)
button.setTitle("Tap", for: .normal)
button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
button.addTarget(self, action: #selector(iterate(_:)), for: .touchUpInside)
view.addSubview(button)
}

@objc func iterate(_ sender: UIButton) {
let tuple = generator.next()
print(String(describing: tuple))
}

}

PlaygroundPage.current.liveView = ViewController()

/*
Optional((offset: 0, element: "Car"))
Optional((offset: 1, element: "Bike"))
Optional((offset: 2, element: "Plane"))
Optional((offset: 3, element: "Boat"))
nil
nil
nil
*/

[1]:

[To see links please register here]

[3]:

[To see links please register here]

Reply

#14
For completeness you can simply iterate over your array indices and use subscript to access the element at the corresponding index:

let list = [100,200,300,400,500]
for index in list.indices {
print("Element at:", index, " Value:", list[index])
}


Using forEach

list.indices.forEach {
print("Element at:", $0, " Value:", list[$0])
}


Using collection `enumerated()` method. Note that it returns a collection of tuples with the `offset` and the `element`:


for item in list.enumerated() {
print("Element at:", item.offset, " Value:", item.element)
}

using forEach:

list.enumerated().forEach {
print("Element at:", $0.offset, " Value:", $0.element)
}

***

Those will print

> Element at: 0 Value: 100
>
> Element at: 1 Value: 200
>
> Element at: 2 Value: 300
>
> Element at: 3 Value: 400
>
> Element at: 4 Value: 500

If you need the array index (not the offset) and its element you can extend Collection and create your own method to get the indexed elements:

extension Collection {
func indexedElements(body: ((index: Index, element: Element)) throws -> Void) rethrows {
var index = startIndex
for element in self {
try body((index,element))
formIndex(after: &index)
}
}
}

***

Another possible implementation as suggested by Alex is to zip the collection indices with its elements:

extension Collection {
func indexedElements(body: ((index: Index, element: Element)) throws -> Void) rethrows {
for element in zip(indices, self) { try body(element) }
}
var indexedElements: Zip2Sequence<Indices, Self> { zip(indices, self) }
}


***

Testing:

let list = ["100","200","300","400","500"]

// You can iterate the index and its elements using a closure
list.dropFirst(2).indexedElements {
print("Index:", $0.index, "Element:", $0.element)
}

// or using a for loop
for (index, element) in list.indexedElements {
print("Index:", index, "Element:", element)
}


This will p[rint


> Index: 2 Element: 300
>
> Index: 3 Element: 400
>
> Index: 4 Element: 500
>
> Index: 0 Element: 100
>
> Index: 1 Element: 200
>
> Index: 2 Element: 300
>
> Index: 3 Element: 400
>
> Index: 4 Element: 500

Reply

#15
We called enumerate function to implements this. like


for (index, element) in array.enumerate() {
index is indexposition of array
element is element of array
}
Reply

#16
Swift 5.x:
-
I personally prefer using the `forEach` method:

list.enumerated().forEach { (index, element) in
...
}

You can also use the short version:

list.enumerated().forEach { print("index: \($0.0), value: \($0.1)") }
Reply

#17
Use .enumerated() like this in functional programming:

list.enumerated().forEach { print($0.offset, $0.element) }

Reply

#18
**Swift 5.x:**

**let list = [0, 1, 2, 3, 4, 5]**

list.enumerated().forEach { (index, value) in
print("index: \(index), value: \(value)")
}

Or,

list.enumerated().forEach {
print("index: \($0.offset), value: \($0.element)")
}

Or,

for (index, value) in list.enumerated() {
print("index: \(index), value: \(value)")
}
Reply

#19
In **iOS 8.0**/**Swift 4.0**+

You can use `forEach`
As per the [Apple docs][1]:

> Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.

let numberWords = ["one", "two", "three"]

numberWords.enumerated().forEach { (key, value) in
print("Key: \(key) - Value: \(value)")
}

[1]:

[To see links please register here]

Reply

#20
If you for whatever reason want a more traditional looking `for` loop that accesses the elements in the array using their index:

```swift
let xs = ["A", "B", "C", "D"]

for i in 0 ..< xs.count {
print("\(i) - \(xs[i])")
}
```
Output:
```console
0 - A
1 - B
2 - C
3 - D
```
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through