ios for循环Swift iOS的退出迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39436722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:05:58  来源:igfitidea点击:

Exit iteration of for loop Swift iOS

iosswiftfor-loopreturnbreak

提问by Alk

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

我有一个内部有 for 循环的函数:

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 returnstatements the code finishes executing for this particular linkin the loop, and the loop moves on to the next link. If NONE of the return statements are reached, I want the dltaskto 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?

基本上我想要实现的是,如果我们到达任何return语句,代码link将在循环中完成对这个特定的执行,并且循环移动到下一个链接。如果没有到达返回语句,我希望dltask执行 。我可以使用一堆 else 语句来实现这一点,但我认为这会使代码变得非常混乱。我这样做正确return吗?

回答by Shades

You're looking for continue:

您正在寻找continue

From Apple's Swift Book:

来自Apple 的 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.

continue 语句告诉循环停止正在执行的操作,并在循环的下一次迭代开始时重新开始。它说“我完成了当前的循环迭代”而没有完全离开循环。

Just replace returnwith continueand it will go back up to the forloop and run it again with the next link.

只需替换returncontinue,它将返回到for循环并使用下一个链接再次运行它。

回答by MedAmine.Rihane

You can use break outeror only breakto exit the loop statement and execute the dltask .

您可以使用break outeror onlybreak退出循环语句并执行 dltask 。

hope it help .

希望有帮助。