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.
Related
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.
I have a set of Strings, which I split it out and save it into an Array, and try to loop it with api as a parameter, but it keep crash with error
index out of range
why is it? Need help pls
You should learn about array basic ideas. This error shows becuse the item you request is not available in the array.
for i in 0...qrCoderArrau.count - 1 {
}
The error is because you are trying to access an element in array with an index greater than its size - 1.
Your qrCodeArray Array is empty also you need to for loop less one to the count of qrCodeArray. So change you for loop like this.
for i in 0..<qrCodeArray.count {
}
In your case for i in 0...qrCoderArray.count { it will execute for loop if your qrCoderArray.count is 0.
To avoid those errors (the last index of an array is count-1) use always
for qrCode in qrCodeArray { ...
rather than an index loop and even if you need the index use
for (index, qrCode) in qrCodeArray.enumerate() { ...
I think best solution is foreach in these situations
for qr in qrCoderArray {
...
}
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"
}
}
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
}
I have a problem with searching for strings in an array. I want to search for one word and if it exists, I want to trace the position of the string in the array.
I believe it should be something like this:
if (myArray contains "11111111") {
trace("*position*")
} else {
trace("cant find it");
}
What kind of syntax are you using there and have you even checked the documentation of the Array class? That should be the first thing you check always, as there is a pretty straightforward method for it:
var arr:Array = ["1111", "2222", "3333"];
trace(arr.indexOf("3333")); //traces the index: 2