现在不要执行一个循环的简明方式,现在C样式for循环将被从Swift 3中删除? [英] A concise way to not execute a loop now that C-Style for loops are going to be removed from Swift 3?
问题描述
n> = 0
来说是完美的。 func fibonacci(n:Int) - > Int {
var memo = [0,1]
for var i = 2;我< = n; i ++ {
memo.append(memo [i-1] + memo [i-2])
}
return memo [n]
}
如果我删除C风格的循环,因为即将到来的Swift 3.0的变化,我得到这样的东西:
func fibonacci(n:Int) - > Int {
var memo = [0,1]
for i in 2 ... n {
memo.append(memo [i-1] + memo [i-2])
return memo
code
$ b罚款为
n> = 2
,对于数字0
和1
带有这个错误信息:
致命错误:无法形成范围结束<开始
解决这个问题最简单的方法是什么,所以它适用于
0
和1
?
(注意:没关系,甚至可取的是,负数会导致应用程序崩溃。)
$ b 注意:我意识到我可以添加一个警戒语句: n> = 2 else {return memo [n]}
...但是我希望有更好的方法来修复只是代码的错误部分(
2 ... n
)。
$ b 例如,如果有一个简洁的方法来创建一个范围,开始,这将是一个更理想的解决方案。解决方案对于n < 2,你可以使用
stride
方法。
let startIndex = 2
let endIndex = n
(步骤:startIndex,through:endIndex,by:1){
memo.append(memo [i-1] + memo [i-2])
}
Imagine we have this code which works perfectly for
n >= 0
.func fibonacci(n: Int) -> Int { var memo = [0,1] for var i = 2; i <= n; i++ { memo.append(memo[i-1] + memo[i-2]) } return memo[n] }
If I remove the C-style for loop due to upcoming changes to Swift 3.0, I get something like this:
func fibonacci(n: Int) -> Int { var memo = [0,1] for i in 2...n { memo.append(memo[i-1] + memo[i-2]) } return memo[n] }
While this works fine for
n >= 2
, it fails for the numbers0
and1
with this error message:fatal error: Can't form Range with end < start
What's the most concise way to fix this code so it works properly for
0
and1
?(Note: It's okay, and even desirable, for negative numbers to crash the app.)
Note: I realize I could add a guard statement:
guard n >= 2 else { return memo[n] }
... but I'm hoping there is a better way to fix just the faulty part of the code (
2...n
).For example, if there was a concise way to create a range that returns zero elements if
end < start
, that would be a more ideal solution.解决方案To do this in a way that works for n < 2, you can use the
stride
method.let startIndex = 2 let endIndex = n for i in stride(from: startIndex, through: endIndex, by: 1) { memo.append(memo[i-1] + memo[i-2]) }
这篇关于现在不要执行一个循环的简明方式,现在C样式for循环将被从Swift 3中删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!