将使用除法的 C 样式 for 循环转换为 Swift 3 [英] Converting a C-style for loop that uses division for the step to Swift 3

查看:32
本文介绍了将使用除法的 C 样式 for 循环转换为 Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个循环,在 Swift 2 中通过除法减少一个整数.

I have this loop, decrementing an integer by division, in Swift 2.

for var i = 128; i >= 1 ; i = i/2  {
   //do some thing
}

不推荐使用 C 风格的 for 循环,那么如何将其转换为 Swift 3.0?

The C-style for loop is deprecated, so how can I convert this to Swift 3.0?

推荐答案

MartinR 的解决方案非常通用且有用,应该成为您工具箱的一部分.

MartinR's solution is very generic and useful and should be part of your toolbox.

另一种方法是重新表述您想要的内容:从 7 到 0 的 2 的幂.

Another approach is to rephrase what you want: the powers of two from 7 down to 0.

for i in (0...7).reversed().map({ 1 << $0 }) {
    print(i)
}

这篇关于将使用除法的 C 样式 for 循环转换为 Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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