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

#1
Is there a function that I can use to iterate over an array and have both index and element, like Python's `enumerate`?

for index, element in enumerate(list):
...
Reply

#2
Starting with Swift 2, the enumerate function needs to be called on the collection like so:

for (index, element) in list.enumerate() {
print("Item \(index): \(element)")
}
Reply

#3
This is the Formula of loop of Enumeration:

for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}

for more detail you can check [Here][1].


[1]:

[To see links please register here]

Reply

#4
I found this answer while looking for a way to do that with a **Dictionary**, and it turns out it's quite easy to adapt it, just pass a tuple for the element.

// Swift 2

var list = ["a": 1, "b": 2]

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

#5
Using `.enumerate()` works, but it does not provide the true index of the element; it only provides an Int beginning with 0 and incrementing by 1 for each successive element. This is usually irrelevant, but there is the potential for unexpected behavior when used with the `ArraySlice` type. Take the following code:

let a = ["a", "b", "c", "d", "e"]
a.indices //=> 0..<5

let aSlice = a[1..<4] //=> ArraySlice with ["b", "c", "d"]
aSlice.indices //=> 1..<4

var test = [Int: String]()
for (index, element) in aSlice.enumerate() {
test[index] = element
}
test //=> [0: "b", 1: "c", 2: "d"] // indices presented as 0..<3, but they are actually 1..<4
test[0] == aSlice[0] // ERROR: out of bounds

It's a somewhat contrived example, and it's not a common issue in practice but still I think it's worth knowing this can happen.
Reply

#6
Starting with Swift 3, it is

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

#7
### Basic enumerate

for (index, element) in arrayOfValues.enumerate() {
// do something useful
}

or with Swift 3...

for (index, element) in arrayOfValues.enumerated() {
// do something useful
}

### Enumerate, Filter and Map

However, I most often use enumerate in combination with map or filter. For example with operating on a couple of arrays.

In this array I wanted to filter odd or even indexed elements and convert them from Ints to Doubles. So `enumerate()` gets you index and the element, then filter checks the index, and finally to get rid of the resulting tuple I map it to just the element.

let evens = arrayOfValues.enumerate().filter({
(index: Int, element: Int) -> Bool in
return index % 2 == 0
}).map({ (_: Int, element: Int) -> Double in
return Double(element)
})
let odds = arrayOfValues.enumerate().filter({
(index: Int, element: Int) -> Bool in
return index % 2 != 0
}).map({ (_: Int, element: Int) -> Double in
return Double(element)
})

Reply

#8
Yes. As of Swift 3.0, if you need the index for each element along with its value, you can use the [`enumerated()` method][1] to iterate over the array. It returns a sequence of pairs composed of the index and the value for each item in the array. For example:

for (index, element) in list.enumerated() {
print("Item \(index): \(element)")
}

Before Swift 3.0 and after Swift 2.0, the function was called `enumerate()`:

for (index, element) in list.enumerate() {
print("Item \(index): \(element)")
}

Prior to Swift 2.0, `enumerate` was a global function.

for (index, element) in enumerate(list) {
println("Item \(index): \(element)")
}

[1]:

[To see links please register here]

Reply

#9
You can simply use loop of enumeration to get your desired result:

**Swift 2:**

for (index, element) in elements.enumerate() {
print("\(index): \(element)")
}

**Swift 3 & 4:**

for (index, element) in elements.enumerated() {
print("\(index): \(element)")
}

Or you can simply go through a for loop to get the same result:

for index in 0..<elements.count {
let element = elements[index]
print("\(index): \(element)")
}

Hope it helps.
Reply

#10
For those who want to use `forEach`.

Swift 4

extension Array {
func forEachWithIndex(_ body: (Int, Element) throws -> Void) rethrows {
try zip((startIndex ..< endIndex), self).forEach(body)
}
}

Or

array.enumerated().forEach { ... }
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

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