When to use enumerate for arrays in Swift? - arrays

I noticed strange things happen when you try to remove or mutate array items in a loop. However, when doing it while calling enumerate() on the array, it works as expected. What is the concept behind it and when should we use enumerate()?

To answer the question from the title, you use enumerate() when you need value's index in addition to the value itself:
If you need the integer index of each item as well as its value, use the enumerate() method to iterate over the array instead.
for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}
enumerate() provides a safe pattern for modifying array elements while iterating over them:
for (index, (var value)) in shoppingList.enumerate() {
if value == "something" {
shoppingList[index] = "something-else"
}
}

Related

Get first entry in Swift array

I can't seem to find much online, but how can I get the first (and then second and third, later on) entry of an array?
My array is being saved to UserDefaults elsewhere and then pulled for use here.
Thanks!
Did you mean to loop through the elements? You can use for in or forEach for that.
var array: [MyType]
for element in array {
print(element)
}
array.forEach { element in
print(element)
}
Maybe you are trying to iterate value from continually with index also
Here is two way you can get first index value than second index value third index value with index also . hope you will get your result .
First way :
var stringArray = ["a","b","C","D","a","i","x","D"]
for (index, element) in stringArray.enumerated() {
print("Item \(index): \(element)")
}
Another way :
for index in 0 ..< stringArray.count {
print(stringArray[index])
}
let me know if its help you.

Is it safe to iterate an array while modifying it?

I know you shouldn't, I kind of know why. But I mean I don't understand my own code once I am trying really to think what's going on.
So I have an array with bunch of objects. I am iterating over it and once I find an object with specific type, I remove it from the array, and add another object into the array. So something like this:
var arr = parent.allchildren() //getting all the children in array
for ele in arr{
if(ele==somethingHere){
parent.remove(ele)
parent.add(new ele) //add new child into child array
}
}
If I have an array of 1,2,3,4,5, and I remove 3 and add a 6 while iterating, the actual array would be 1,2,4,5,6 but the array I am iterating would still be 1,2,3,4,5.
Which I think it would be fine, because at the end I still get what I want, which removed the element and added the element I need. However modifying the list while iterating it is bad and you shouldn't do that, but for my case I think it does what I need. What could be the potential issue in my case that I can't see?
One thing you may want to think about doing is making all of the changes at the end of the iteration. Instead of making the changes one by one, record the changes you want to make while iterating, and then actually make those changes once your loop is finished.
For example, you could make an array of elements to remove, and an array of elements to add.
//Our array where we record what we want to add
var elementsToAdd = [Any]()
//Our array of what elements we want to remove. We record the index at
//which we want to remove the element from the array
var indexesToRemoveAt = [Int]()
//Getting all the children in array
var arr = parent.allchildren()
//Enumerating an array allows us to access the index at which that
//element occurs. For example, the first element's index would be 0,
//the second element's index would be 1, the third would be 2, and so
//on
for (index,ele) in arr.enumerated() {
if(ele == somethingHere) {
indexesToRemoveAt.append(index)
elementsToAdd.append(newEle)
}
}
//Now that we have recorded the changes we want to make, we could make
//all of the changes at once
arr.remove(at: indexesToRemoveAt)
arr.append(contentsOf: elementsToAdd)
Note that removing array elements at multiple indexes would require the following extension to Array. If you wanted to avoid creating this extension, you could always just loop through the array of indexes and tell the array to remove at each individual index. All this extension function is really doing is looping through the indexes, and removing the array element at said index.
Array extension to remove elements at multiple indexes:
extension Array {
//Allows us to remove at multiple indexes instead of just one
mutating func remove(at indexes: [Int]) {
for index in indexes.sorted(by: >) {
if index <= count-1 {
remove(at: index)
}
}
}
}
I just tested in a playground with the following code:
var arr = ["hi", "bye", "guy", "fry", "sky"]
for a in arr {
if arr.count >= 3 {
arr.remove(at: 2)
}
print(a)
}
print(arr)
This prints:
hi
bye
guy
fry
sky
["hi", "bye"]
So it looks like when you use a for-in loop in Swift, the array is copied and changes you make to it will not affect the array you are iterating over. To answer your question, as long as you understand that this is the behavior, there's nothing wrong with doing this.

How to loop through arrays starting at different index while still looping through entire array in swift?

I want to start loop through array at index (say “5” or any other) instead of beginning of the array in swift
for (index, value) in array.enumerate() {
// do something
}
Use dropFirst to ignore the first items:
for (index, value) in array.enumerated().dropFirst(5) {
// your code here
}
Use the where clause
for (index, value) in array.enumerate() where index > 4 { ...
By the way: Update your Swift version. Swift 2 is dead

Find Array Item Number in a For Statement

I'm using a for statement to loop through items in an array to find the item's value. On occasion however, I need to find out what that item's count is in the array (not just the item value), but can't seem to figure out how to do this. Below is what I've been trying which has given me some sort of result, but not what I need, everything else I've tried has resulted in an error:
for elements in myArray {
println(elements) // gives me the value
println(elements.items) // gives me nil
}
Any help would be much appreciated.
Well an easy way to do that is:
for index in 0..<myArray.count {
println(myArray[index]) // value
println(index) // count
}
If you know what kind of value you're looking for, you can also use the find() method:
let value = 13
if let index = find(myArray, value) {
println(myArray[index]) // item in the array with the value you were searching for
}
You can use enumerate() to get the elements of an array (or any
sequence) together with the corresponding index:
for (index, element) in enumerate(myArray) {
println(element) // current element
println(index) // index of current element
}

Swift sort array of objects based on boolean value

I'm looking for a way to sort a Swift array based on a Boolean value.
I've got it working using a cast to NSArray:
var boolSort = NSSortDescriptor(key: "selected", ascending: false)
var array = NSArray(array: results)
return array.sortedArrayUsingDescriptors([boolSort]) as! [VDLProfile]
But I'm looking for the Swift variant, any ideas?
Update
Thanks to Arkku, I've managed to fix this using the following code:
return results.sorted({ (leftProfile, rightProfile) -> Bool in
return leftProfile.selected == true && rightProfile.selected != true
})
Swift's arrays can be sorted in place with sort or to a new array with sorted. The single parameter of either function is a closure taking two elements and returning true if and only if the first is ordered before the second. The shortest way to use the closure's parameters is by referring to them as $0 and $1.
For example (to sort the true booleans first):
// In-place:
array.sort { $0.selected && !$1.selected }
// To a new array:
array.sorted { $0.selected && !$1.selected }
(edit: Updated for Swift 3, 4 and 5, previously sort was sortInPlace and sorted was sort.)
New (for Swift 1.2)
return results.sort { $0.selected && !$1.selected }
Old (for Swift 1.0)
Assuming results is of type [VDLProfile] and VDLProfile has a Bool member selected:
return results.sorted { $0.selected < $1.selected }
See documentation for sorted
Swift’s standard library provides a function called sorted, which sorts an array of values of a known type, based on the output of a sorting closure that you provide
reversed = sorted(array) { $0 > $1 }
reversed will be a new array which will be sorted according to the condition given in the closure.

Resources