Swift 2.0的新控件传输语句(标签) [英] New control transfer statements (labels) for Swift 2.0

查看:81
本文介绍了Swift 2.0的新控件传输语句(标签)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我听说过它,所以我不能停止将它与旧的Basic语言的goto命令进行比较,这在当时经验丰富的程序员中从未得到过很好的接受.

Since I hear about it I can't stop compare it with the goto command from the good and old Basic language, what never was well accepted from experient programmers at the time.

控制流传输的某些用法看起来不错,如下面的示例所示:

Some uses of the control flow transfer looks ok, like in example below:

outer: for i in 1...100{
  for j in 1...100{
    print("\(i), \(j)")
    if j == 10 {
      break outer
    }
  }
}

但是控制流传输使用的局限性是什么?

But what are the limitations for the control flow transfer use?

开始时会不好用吗?

如果使用它是一种不好的做法,为什么又回来了?

If its use was such a bad practice why it is back?

推荐答案

您可以在循环语句,if语句或switch语句前加一个带有冒号(:)的语句标签,使用break和continue语句作为前缀.更改循环语句或switch语句中的控制流.

You can prefix a loop statement, an if statement, or a switch statement with a statement label followed by a colon (:) ,break and continue statements are used to change control flow in a loop statement or a switch statement.

break语句中断当前循环执行,而继续则中断当前循环.

break statement breaks the current loop execution where as continue just breaks current iteration.

考虑:

     firstLoop :for j in 0...1{
      secondLoop: for i in 0...10{
        if (i % 2) == 0{
          if (i == 4){
             break firstLoop
          }
          print(i)
         }
       }
      }

输出将为: 0,2

如果我们将 break firstloop 替换为 break secondLoop ,则o/p将为: 0,2,0,2

If we replace break firstloop by break secondLoop o/p Will be: 0,2,0,2

如果我们将 break firstloop 替换为 continue ,则o/p将为: 0,2,6,8,10,0,2,6,8 ,10

If we replace break firstloop by continue o/p Will be: 0,2,6,8,10,0,2,6,8,10

如果将 break firstloop 替换为 continue firstloop ,则继续o/p将再次为: 0,2,0,2

If we replace break firstloop by continue firstloop continue o/p Will be again : 0,2,0,2

如果继续后跟一个语句标签,则它将停止该语句标签的当前迭代,而不是语句标签所指向的循环.

If continue is followed by a statement label then it will stop the current iteration of that statement label not the loop pointed by statement label.

转到VS语句标签

. goto是一种无条件分支,您可以在程序中的任何位置分支,不建议使用goto语句,因为它会改变逻辑顺序.

. goto is a kind of unconditional branching ,where you can branch anywhere in the program,The goto statement is discouraged , because it alters the sequential flow of logic .

为什么使用语句标签,它是什么?限制?

.只有当将continue和break写入具有相同语句标签的循环内时,continue和break才能使用语句标签,这样代码将更加安全.它使程序员的工作变得轻松,当然,您不能使用continue,break和statement直接将其分支到程序的任何部分.Label被认为是一种限制.

. where as continue and break can make use of statement label if and only if it is written inside the loop which has same statement label which it is using so the code will be more safer. It makes programers life easy , off course you can't directly branch out to any part of program using continue,break and statement Label it can be considered as a limitation.

这篇关于Swift 2.0的新控件传输语句(标签)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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