Skip to content

[SR-14265] Warn when trying to override the range values in a loop #56625

Open
@swift-ci

Description

@swift-ci
Previous ID SR-14265
Radar rdar://problem/74652010
Original Reporter arlomedia (JIRA User)
Type Improvement
Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Improvement, DiagnosticsQoI
Assignee None
Priority Medium

md5: 24c62d084c635252a16671e4ed35b018

Issue Description:

I'm converting a project from Objective-C, and I have a few cases where I change the index of a for loop on the fly, like this:

for (int i=1; i<[items count]; i++) {
    if ([[items objectAtIndex:i] hasPrefix:@"-"]) {
        isGroup = TRUE;
        i = i + 3;
    }
}

After converting to Kotlin, I didn't see any compiler warnings or errors, so I expected this to work the same way:

for var i in 0..<items.count {
    if items[i].hasPrefix("-") {
        isGroup = true
        i = i + 3
    }
}

But the change to i is essentially ignored (reset on each iteration). I've since found some explanations of why this behaves the way it does, and I can rewrite the code to get the same behavior. But I would like to see the compiler flag this so I know it's a problem before it shows up as a bug in my app.

The same construct works in Java and Kotlin, so this change would also help developers coming from those languages.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions