2

In swift, I always used the C notation like:

for (var i=0;i<mybuffer.count;i++) {}

Now in 3.0 this can not be used. The problem is that using

for i in..<mybuffer.count {} 

will not check the value of mybuffer.count for each iteration, which leads to index out of range, in case the mybuffer.count changes.

Is there a way to overcome this?

I could use a while statement, but I guess that there must be a way to have a for in loop with a dynamic range, right?

2
  • There doesn't have to be such a thing. In general, modifying the size of the array in a loop is discouraged. It's a common source of bugs in C because it creates tricky corner cases (it's an error to do this in ObjC with NSMutableArray). In most cases, Swift pushes you towards treating mybuffer as immutable, and creating a new array (using tools like map). It is still possible to go the other way (and there are good reasons in some cases), but it stands out by requiring while syntax. Commented Sep 29, 2016 at 1:07
  • 1
    @RobNapier This would not be an error in Objective-C with NSMutableArray. That would only be an issue with fast enumeration, not with a "normal" for loop. Commented Sep 29, 2016 at 3:57

1 Answer 1

4

One alternative would be to use a while loop:

var i = 0
while i < mybuffer.count {
    // do stuff
    i += 1
}
Sign up to request clarification or add additional context in comments.

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.