I have been trying to take the length of an array and use that length to set the amount of times that my loop should execute. This is my code:
if notes.count != names.count {
notes.removeAllObjects()
var nameArrayLength = names.count
for index in nameArrayLength {
notes.insertObject("", atIndex: (index-1))
}
}
At the moment I just get the error:
Int does not have a member named 'Generator'
Seems like a fairly simple issue, but I haven't yet figured out a solution. Any ideas?
Swift – Array Size To get the size of an array in Swift, use count function on the array. Following is a quick example to get the count of elements present in the array. array_name is the array variable name. count returns an integer value for the size of this array.
You use the for-in loop to iterate over a sequence, such as items in an array. This example uses a for-in loop to iterate over the subviews and set their translatesAutoresizingMaskIntoConstraints to false . There also another variation of looping over a collection, that is forEach(_:) .
Swift for-in Loop In Swift, the for-in loop is used to run a block of code for a certain number of times. It is used to iterate over any sequences such as an array, range, string, etc. Here, val accesses each item of sequence on each iteration. Loop continues until we reach the last item in the sequence .
Swift has a helpful stride() , which lets you move from one value to another using any increment – and even lets you specify whether the upper bound is exclusive or inclusive.
You need to specify the range. If you want to include nameArrayLength
:
for index in 1...nameArrayLength {
}
If you want to stop 1 before nameArrayLength
:
for index in 1..<nameArrayLength {
}
for i in 0..< names.count {
//YOUR LOGIC....
}
for name in 0..< names.count {
//YOUR LOGIC....
print(name)
}
for (index, name) in names.enumerated()
{
//YOUR LOGIC....
print(name)
print(index)//0, 1, 2, 3 ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With