【问题标题】:Exit iteration of for loop Swift iOSfor loop Swift iOS的退出迭代
【发布时间】:2017-01-19 02:08:10
【问题描述】:

我有一个函数,里面有一个 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.....
    })
  }
}

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

【问题讨论】:

    标签: ios swift for-loop return break


    【解决方案1】:

    你正在寻找continue:

    来自Apple's Swift Book

    continue 语句告诉循环停止它正在做的事情并开始 再次在循环的下一次迭代开始时。它说 “我完成了当前的循环迭代”而不离开循环 完全一致。

    只需将return 替换为continue,它就会回到for 循环并使用下一个链接再次运行它。

    【讨论】:

      【解决方案2】:

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

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-08
        • 2021-06-06
        • 1970-01-01
        • 1970-01-01
        • 2017-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多