Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop based on array length in Swift

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?

like image 330
user3746428 Avatar asked Nov 02 '14 00:11

user3746428


People also ask

How do I find the length of an array in Swift?

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.

How do I iterate a list in Swift?

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(_:) .

How do you write a for loop in Swift 5?

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 .

What is stride in Swift?

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.


2 Answers

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 {
}
like image 189
vacawama Avatar answered Oct 09 '22 18:10

vacawama


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 ...
}
like image 43
Ketan Patel Avatar answered Oct 09 '22 18:10

Ketan Patel