Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit iteration of for loop Swift iOS

I have a function with a for loop inside of it:

func example() {
  // create tasks
  for link in links {
    let currIndex = links.indexOf(link)

    if let im = story_cache?.objectForKey(link) as? UIImage {
      if ((currIndex != nil) && (currIndex < content.count)) {
        if (content[currIndex!].resource_type == "image") {
          content[currIndex!].image = im
          return
        }
      }
    } else {
      if ((currIndex != nil) && (currIndex < content.count)) {
        if (content[currIndex!].resource_type == "video") {
          let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
          let documentsDirectory : NSString = paths[0]
          let appFile = documentsDirectory.stringByAppendingPathComponent(content[currIndex!].id! + ".mov")
          let local_URL = NSURL(fileURLWithPath: appFile)
          if let cached_URL = story_cache?.objectForKey(local_URL) as? NSURL {
            content[currIndex!].videoURL = cached_URL
            return
          }
        }
      }
    }

    let dltask = session.dataTaskWithURL(link, completionHandler: { (data, response, error) in  
      // MORE CODE.....
    })
  }
}

Basically what I wanna achieve is that if we reach any of the return statements the code finishes executing for this particular link in the loop, and the loop moves on to the next link. If NONE of the return statements are reached, I want the dltask to be executed. I could achieve this using a bunch of else statements but I think that would make the code quite messy. Am I doing this right with using return?

like image 984
Alk Avatar asked Sep 11 '16 13:09

Alk


People also ask

What does exit () do in Swift?

exit() Terminates the current thread.

How do you stop an infinite loop in Swift?

I was able to halt my loop by typing the iteration variable setting (that would stop the loop) somewhere else like in a text editor then right click pasting the text into the loop. In your case, right-click pasting l = 0 right before the last bracket should work.

How do you skip a loop cycle?

So, use continue when you want to skip the rest of the current loop iteration, and use break when you want to skip all remaining loop iterations.


2 Answers

You're looking for continue:

From Apple's Swift Book:

The continue statement tells a loop to stop what it is doing and start again at the beginning of the next iteration through the loop. It says “I am done with the current loop iteration” without leaving the loop altogether.

Just replace return with continue and it will go back up to the for loop and run it again with the next link.

like image 50
Shades Avatar answered Oct 17 '22 17:10

Shades


You can use break outer or only break to exit the loop statement and execute the dltask .

hope it help .

like image 26
MedAmine.Rihane Avatar answered Oct 17 '22 18:10

MedAmine.Rihane