swift - for循环中的额外数据

标签 swift for-loop textures

我正在尝试执行一个 for 循环以将一些数据附加到另一个数组。我的文件夹中只有 5 个项目,但它给了我 6 个项目。我不确定要对我的 for 循环做什么。

enter image description here

我的代码是这样的:

// TextureAtlas been populated by the Images folder
    textureAtlas = SKTextureAtlas(named: "RockImages")

    // Adds the images from the textureAtlas to the textureArray in order
    for i in 0...textureAtlas.textureNames.count {
        let Name = "rock_\(i).png"
        textureArray.append(SKTexture(imageNamed: Name))
    }

这是我打印出 textureArray 时得到的结果:

enter image description here

最佳答案

解决眼前的问题

这就是您不应该手动编写索引范围的原因。

for i in 0...textureAtlas.textureNames.count

应该是

for i in 0..<textureAtlas.textureNames.count

如果您只是使用,将完全避免发生此错误的可能性

for i in textureAtlas.textureNames.indices

但还有更好的办法

您已经有了可用的纹理名称。无需获取索引,也无需使用 let name = "rock_\(i).png" 将它们手动转换为名称。只是做:

for name in textureAtlas.textureNames {
    textureArray.append(SKTexture(imageNamed: Name))
}

等等,还有更多!

您应该避免这种创建空数组并重复向其中添加元素的模式。这是很多样板代码,速度很慢,并且它要求您的数组是可变的,即使它不需要是可变的。使用 map(_:)相反。

let textureArray = textureAtlas.textureNames.map(SKTexture.init(imageNamed:))

关于swift - for循环中的额外数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41108220/

相关文章:

c - Quad 上的纹理贴图不起作用

ios - 将动画应用于 UIKit 类的每个实例?

R循环创建带有2个计数器的数据帧

javascript - 如何减少 JavaScript 代码的执行时间

Bash for 带空格的循环

cuda - 绑定(bind)的 CUDA 纹理读数为零

Three.js 立方体黑色但我添加了纹理?

ios - Swift 将多个 IBOutlet 放在一个数组中

ios - 如何重新加载 tableviewcell 中的 collectionview

ios - Locale.current 在设备上报告错误的语言