在此循环中,我们有可能在处理循环时减少循环中的项目数量。此代码在 Obj-C 中运行良好,但 Swift 循环不会收到项目已被删除的消息并最终导致数组溢出。
在 Objective-C 中,我们有:
for(int i = 4; i < staticBlocks.count; i++)
{
PlayerSprite* spr = [staticBlocks objectAtIndex:i];
[spr setPosition:CGPointMake(spr.position.x, spr.position.y-1)];
if(spr.position.y < -1000)
{
[staticBlocks removeObject:spr];
[spr removeFromParent];
}
if(spr.blockTypeIndex == Block_Type_Power_Up)
{
[spr update];
}
}
在 Swift 中我知道这些选项:
//for i in 4.stride(to: staticBlocks.count, by: 1){ //crashes
//for i in 4..<staticBlocks.count{ //crashes
for var i = 4; i < staticBlocks.count; i += 1 { //works, but is deprecated
let spr = staticBlocks.objectAtIndex(i) as! PlayerSprite
spr.position = CGPointMake(spr.position.x, spr.position.y-1)
if(spr.position.y < -1000)
{
staticBlocks.removeObject(spr)
spr.removeFromParent()
//break
}
if(spr.blockTypeIndex == k.BlockType.PowerUp)
{
spr.update()
}
}
在这种特定情况下,使用break语句(当前已被注释掉)来终止循环并防止崩溃对我来说确实不是问题,但这似乎不是正确的修复方法。我想总有一天我需要知道如何正确地做到这一点。是否有一种未弃用的方法来执行 for 循环,即处理每次传递的计数?
一个相关的、未回答的问题。 Is the for loop condition evalutaed each loop in swift?
最佳答案
我不知道如何链接到特定答案,但这段代码满足了我的需要。现在标记为重复。
Removing from array during enumeration in Swift?
var a = [1,2,3,4,5,6]
for (i,num) in a.enumerate().reverse() {
a.removeAtIndex(i)
}
关于objective-c - for 循环的差异。 swift vs. Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38888336/