For loop based on array length in Swift
46,197
Solution 1
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 {
}
Solution 2
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 ...
}
Solution 3
In Swift 3 and Swift 4 you can do:
for (index, name) in names.enumerated()
{
...
}
Author by
user3746428
Updated on July 09, 2022Comments
-
user3746428 almost 2 years
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?