24

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?

3
  • You are trying to insert an object in an empty NSMutableArray, in this case you should use .addObject Commented Nov 2, 2014 at 1:05
  • If index is already occupied, the objects at index and beyond are shifted by adding 1 to their indices to make room. Commented Nov 2, 2014 at 1:06
  • 1
    Note that NSArray objects are not like C arrays. That is, even though you specify a size when you create an array, the specified size is regarded as a “hint”; the actual size of the array is still 0. This means that you cannot insert an object at an index greater than the current count of an array. For example, if an array contains two objects, its size is 2, so you can add objects at indices 0, 1, or 2. Index 3 is illegal and out of bounds; if you try to add an object at index 3 (when the size of the array is 2), NSMutableArray raises an exception. Commented Nov 2, 2014 at 1:06

4 Answers 4

39

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 {
}
Sign up to request clarification or add additional context in comments.

1 Comment

@HoldOffHunger, I started at 1 so that the OP's notes.insertObject("", atIndex: (index-1)) wouldn't crash.
18
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 ...
}

2 Comments

Just awesome. Working as expected.
it should be for i in 0..<names.count {. "check for space after <"
4

In Swift 3 and Swift 4 you can do:

for (index, name) in names.enumerated()
{
     ...
}

2 Comments

@MicheleDall'Agata I'm also from the C era. Great to have you back as a programmer!
Ah, just doing some Swift self training. The beginning has been atrocious! :-D Especially with those damn escaping closures..
1

You can loop over the Array's indices

for index in names.indices {
    ...
}

If you are just wanting to fill an array with empty strings you could do

notes = Array(repeating: "", count: names.count)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.