c-style for statement deprecated with a twist

时间:2016-04-15 15:00:13

标签: swift for-loop compiler-warnings deprecated

I've been coding for about 2 years, but I am still terrible at it. Any help would be much appreciated. I have been using the following code to set my background image parameters, after updating to Xcode 7.3 I got the warning 'C-Style statement is deprecated and will be removed':

for var totalHeight:CGFloat = 0; totalHeight < 2.0 * Configurations.sharedInstance.heightGame; totalHeight = totalHeight + backgroundImage.size.height  {...}

Just to clarify, I have looked at a few other solutions/examples, I have noticed that one workaround is to use the for in loop, however, I just can't seem to wrap my head around this one and everything I have tried does not seem to work. Again, any help would be much appreciated.

2 个答案:

答案 0 :(得分:4)

始终有效的策略是将for循环转换为此模式行的while循环:

for a; b; c {
  // do stuff
}

// can be written as:

a // set up
while b { // condition
  // do stuff
  c // post-loop action 
}

因此,在这种情况下,您的for循环可以写为:

var totalHeight: CGFloat = 0
while totalHeight < 2.0 * Configurations.sharedInstance.heightGame {
  // totalHeight = totalHeight + backgroundImage.size.height can be
  // written slightly more succinctly as:
  totalHeight += backgroundImage.size.height
}

但是你是对的,可能的首选解决方案是使用for in代替。

for in与C风格forwhile略有不同。您不直接自己控制循环变量。相反,语言将循环“序列”产生的任何值。序列是符合协议(SequenceType)的任何类型,该协议可以创建将逐个提供该序列的生成器。很多东西都是序列 - 数组,字典,索引范围。

有一种称为步幅的序列,您可以使用for in来解决此特定问题。步幅有点像范围,更灵活地增加。您指定一个“by”值,该值是每次变化的数量:

for totalHeight in 0.stride(to: 2.0 * Configurations.sharedInstance.heightGame,
                            by: backgroundImage.size.height) {

    // use totalHeight just the same as with the C-style for loop

}

注意,有两种跨步方式,to:(最多但不包括,如果您使用过<)和through:(包括,等等) <=)。

使用for in循环获得的好处之一是循环变量不需要使用var声明。相反,每次循环都会得到一个全新的不可变(即常量)变量,这有助于避免一些微妙的错误,尤其是关闭变量捕获。

你偶尔还需要while形式(例如,没有内置类型允许你每次都加倍计数器),但是对于日常使用来说,它有一种整洁(并且希望更具可读性)的方式没有这样做。

答案 1 :(得分:1)

最好使用while循环:

var totalHeight: CGFloat = 0
while totalHeight < 2.0 * Configurations.sharedInstance.heightGame {
    // Loop code goes here

    totalHeight += backgroundImage.size.height
}