本文介绍了现在不要执行一个循环的简明方式,现在C样式for循环将被从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 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 numbers 0 and 1 with this error message:What's the most concise way to fix this code so it works properly for 0 and 1? (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 = 2let endIndex = nfor i in stride(from: startIndex, through: endIndex, by: 1) { memo.append(memo[i-1] + memo[i-2])} 这篇关于现在不要执行一个循环的简明方式,现在C样式for循环将被从Swift 3中删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
11-02 12:57