优雅的Swift方式来处理for循环中的负指数 [英] Elegant Swift way to handle negative index in for loop

查看:589
本文介绍了优雅的Swift方式来处理for循环中的负指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的 Swift ,并试图找到一个优雅的方式来处理一个for循环变量,可以是负面的。

  func funForLoops(_ loop:Int){
for i in 0 ..< loop {
print(Hello \(i) )
}
}
funForLoops(1)//打印Hello 0
funForLoops(0)//不执行
funForLoops(-1)//运行时错误致命错误:无法形成范围与upperBound< lowerBound

是否有更简单这样比这个检查方式:

pre $ code if(loop> = 0){
for i in 0 .. < loop {
print(Hello \(i))
}
}

或者这个:

  for i in 0 ..<(loop> = 0?循环:0){


解决方案

如果它是消极的,什么都不要做(这不是显而易见的;你可能意思是减量,这就是为什么它会是模棱两可的它不是一个例外)你想要的语法是:

  for i in 0 ..< max(0,loop ){} 

这是一个很好的语法,但在大多数情况下,出乎意料地是消极的,你在程序结构上存在更深层次的问题,应该尽早解决问题。


I'm new to Swift and trying to find an elegant way to handle a for loop variable that can be negative.

func funForLoops(_ loop:Int) {
    for i in 0..<loop {
        print("Hello \(i)")
    }
}
funForLoops(1) // prints Hello 0
funForLoops(0) // doesn't execute
funForLoops(-1) // runtime error "fatal error: Can't form Range with  upperBound < lowerBound"

Is there a simpler way to check this than this:

if (loop >= 0) {
    for i in 0..<loop {
        print("Hello \(i)")
    }
}

Or this:

for i in 0..<(loop >= 0 ? loop : 0) {

解决方案

On the assumption you mean "if it's negative, do nothing," (which is not obvious; you might mean "decrement," which is why it would be ambiguous if it weren't an exception) the syntax you want is:

for i in 0..<max(0, loop) { }

This is a fine syntax when it is necessary, but in most cases if the value can be surprisingly negative, you have a deeper problem in the structure of the program and should have resolved the issue sooner.

这篇关于优雅的Swift方式来处理for循环中的负指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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