objective-c - for 循环的差异。 swift vs. Objective-C

标签 objective-c swift for-loop

在此循环中,我们有可能在处理循环时减少循环中的项目数量。此代码在 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/

相关文章:

ios - 在 Debug模式下获取有关对象的更多详细信息

ios - Xcode - 如何在不更改 UIScreen 大小的情况下添加 xib 启动屏幕

ios - 关闭堆栈中较低的 ViewController 并不像预期的那样表现

iphone - 排除不支持多任务处理的设备

python - 如何编写一个接受正整数 N 并返回前 N 个自然数的列表的函数

java - 为什么我无法从此枚举中获取所需的数据?

javascript - 循环一个变量的items(list),每个item也是一个带items(list)的变量

ios - SceneKit:使用平移手势移动不在原点的节点

ios - 如何以编程方式将用户名和密码存储在自动填充中?

swift - 使用由单例组成的默认值初始化 UIViewController