我无法理解错误在哪里。请帮我解决这个问题。
这是我的代码:
import SpriteKit
class EncounterManager {
let encounterNames: [String] = ["EncounterName1",
"EncountersName2",
"EncountersName3"]
var encounters: [SKNode] = []
var currentEncounterIndex:Int?
var previousEncounterIndex:Int?
init() {
for encounterFileName in encounterNames {
let encounter = SKNode()
if let encounterScene = SKScene(fileNamed: encounterFileName) {
for placeholder in encounterScene.children {
if let node = placeholder as? SKNode {
switch node.name! {
case "N" :
let n = N()
n.spawn(encounter, position: node.position)
case "NN":
let nn = NN()
nn.spawn(encounter, position: node.position)
case "NNN":
let nnn = NNN()
nnn.spawn(encounter, position: node.position)
case "GGG":
let ggg = GGG()
ggg.spawn(encounter, position: node.position)
case "GG":
let gg = GG()
gg.spawn(encounter, position: node.position)
case "G":
let g = G()
g.spawn(encounter, position: node.position)
case "F":
let f = F()
ff.spawn(encounter, position: node.position)
default:
print("Name error: \(node.name)")
}
}
}
}
}
}
func addToWorld(world:SKNode) {
for index in (encounters.count).stride(through: 0, by: -1) {
encounters[index].position = CGPoint(x: -2000, y: index * 1000)
world.addChild(encounters[index])
}
}
}
这是来自控制台的错误:
fatal error: Index out of range
这是错误行:
encounters[index].position = CGPoint(x: -2000, y: index * 1000)
这是行错误:
EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP, subcode=0x0)
我试图在互联网上找到有关此问题的一些信息,但无法找到它。
答案 0 :(得分:1)
更改此行:
for index in (encounters.count).stride(through: 0, by: -1)
对此:
for index in (encounters.count.predecessor()).stride(through: 0, by: -1)
您收到错误是因为使用第一个版本,步幅从encounters.count
开始,这是最后一个有效索引的后面。