Swift - 如何知道循环何时结束? [英] Swift - How to know when a loop has ended?

查看:158
本文介绍了Swift - 如何知道循环何时结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请原谅我,因为我非常刚接触swift,并且编程一般。

Please, forgive me as i'm very new to swift, and programming in general.

当我说'我时,请相信我'我们努力了解这一点,但我根本不能并且非常感谢任何帮助。

Believe me when I say I've tried hard to understand this, but I simply can't and would greatly appreciate any help.

说我有这个功能:

func loop() {
  for var i=0; i<5; i++ {
  println(i)
  }
}

和一旦这个循环完成并完成运行,我想打印到日志循环已完成,我该怎么做?如果我这样做:

and I wanted to print to the logs "loop has finished" once this loop had completed and finished running, how would I do this? If i do:

func loop() {
  for var i=0; i<5; i++ {
  println(i)
  println("loop has finished")
  }
}

然后在每次i递增后打印循环已完成。

then "loop has finished" gets printed after every time i is incremented.

我已经尝试过阅读闭包和完成处理程序了,但是现在一切都在我脑海中,我真的不明白我是如何完成任务的以上。

I've tried reading into closures and completion handlers, but it's all going over my head at the moment and I don't really understand how i'd achieve the task above.

如果有一位天使可以告诉我如何完成上述例子,我将欠你的债务。

If there's an angel that can show me how I'd complete my above example, I'd be in your debt.

感谢您对我目前可怜的知识的耐心!

Thankyou for your patience with my currently pathetic knowledge!

推荐答案

产生与其他人发布的结果相同的结果但使用基本闭包语法:

To produce the same result as what others have posted but with basic closure syntax:

func printFunction() {
    println("loop has finished")
}

func loopWithCompletion(closure: () -> ()) {
    for var i=0; i<5; i++ {
        println(i)
    }
    closure()
}

您可以这样称呼它:

 loopWithCompletion(printFunction)

Swift 3更新:

func printFunction() {
    print("loop has finished")
}

// New for loop syntax and naming convention
func loop(withCompletion completion: () -> Void ) {
    for i in 0 ..< 5 {
        print(i)
    }
    completion()
}

然后这样称呼:

loop(withCompletion: printFunction)

loop {
    print("this does the same thing")
}

这篇关于Swift - 如何知道循环何时结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆