退出for循环Swift iOS的迭代

Alk*_*Alk 17 for-loop return break ios swift

我有一个带有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.....
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*des 38

您正在寻找continue:

来自Apple的Swift Book:

continue语句告诉循环停止它正在做什么,并在循环的下一次迭代开始时再次启动.它说"我完成了当前的循环迭代"而没有完全离开循环.

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


Med*_*ane 13

您可以使用break outer或仅break退出循环语句并执行dltask.

希望它有所帮助.