ikevin8me
ikevin8me

Reputation: 4313

Swift language: how to continue after a guard statement?

Why the continue is flagging an error:

continue is only allowed inside a loop

private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
    guard unloadedImagesRows[forLocation] != nil else {
        unloadedImagesRows[forLocation] = [Int]()
        continue
    }
    unloadedImagesRows[forLocation]!.append(row)
}

How can I resolve this?

Upvotes: 3

Views: 8904

Answers (3)

nebs
nebs

Reputation: 4989

If you really want to use guard you could do this:

private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
    guard unloadedImagesRows[forLocation] != nil else {
        unloadedImagesRows[forLocation] = [row]
        return
    }
    unloadedImagesRows[forLocation]!.append(row)
}

But personally in this case I'd find an if slightly easier to read.

Upvotes: 1

rob mayoff
rob mayoff

Reputation: 386018

You cannot “continue” the current scope (in your case, the addToUnloadedImagesRow(_:forLocation:) method) after a guard statement. The guard statement's else-block must leave the current scope.

Anyway, looking at your code, I think you just want to do this:

private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
    if unloadedImagesRows[forLocation] == nil {
        unloadedImagesRows[forLocation] = [Int]()
    }
    unloadedImagesRows[forLocation]!.append(row)
}

Upvotes: 2

Mahendra
Mahendra

Reputation: 8924

continue statement should be used in loops.

if you want to check multiple conditions then you should use an if statement instead of guard.

Upvotes: 6

Related Questions