为什么我的"如果"也不是"否则"正在执行的陈述?

时间:2017-01-12 04:30:56

标签: ios arrays swift sprite-kit

在每个声明中,我定义var" highScores"是的,但程序似乎跳过了,告诉我它甚至在运行任何一个声明之前是零。我想至少,我的打印语句会在继续之前执行。

    func retrieveScores() {

    var highScores: [Int]?

    if var prevHighScores = UserDefaults.standard.array(forKey: "highScores") as? [Int] {

        print("there were previous high scores")

        if displayedScore > prevHighScores.last! {

            prevHighScores.insert(displayedScore, at: 0)
            highScores = prevHighScores.sorted()
        }

    } else {

        print("there were NOT previous high scores")

        highScores = Array(repeating: Int(0), count: 10)
        highScores![0] = displayedScore
        UserDefaults.standard.set(highScores, forKey: "highScores")
    }

    // THIS IS WHERE THE ERROR OCCURS  //
    for index in 0...highScores!.count - 1 {

        let thisLabel = SKLabelNode(text: String(describing: highScores![index]))
        thisLabel.color = UIColor.orange
        thisLabel.position = CGPoint(x: 100, y: (view!.bounds.height * 0.75) -
            CGFloat((index+1) * 25))
        thisLabel.fontName = "Cochin"
        thisLabel.fontSize = 20

        addChild(thisLabel)
    }
}

2 个答案:

答案 0 :(得分:0)

if var prevHighScores = UserDefaults.standard.array(forKey: "highScores") as? [Int] {

应该阅读

if let prevHighScores = UserDefaults.standard.array(forKey: "highScores") as? [Int] {

虽然因为我感到无聊,但我还是把它清理了一下。 我在这里使用了nil合并算子。因此,如果它没有从UserDefaults获取高分,它将返回10个0的数组

func retrieveScores() {

    var highScores = UserDefaults.standard.array(forKey: "highScores") as? [Int] ?? [Int](repeating: 0, count: 10)

    if displayedScore > highScores.min() ?? 0 {
        highScores = (highScores + [displayedScore]).sorted(by: >)
        highScores.removeLast()
        UserDefaults.standard.set(highScores, forKey: "highScores") 
    }


    for (index, score) in highScores.enumerated() {

        let thisLabel = SKLabelNode(text: "\(score)")
        thisLabel.color = UIColor.orange
        thisLabel.position = CGPoint(x: 100, y: (view!.bounds.height * 0.75) -
            CGFloat((index+1) * 25))
        thisLabel.fontName = "Cochin"
        thisLabel.fontSize = 20

        addChild(thisLabel)
    }

}

答案 1 :(得分:0)

问题在于,如果您输入if分支(prevHighScores已设置),然后displayedScore <= prevHighScores.last!,则永远不会设置highScores

您已将highScores声明为可选,稍后强行展开,从而使您的代码不必要地不安全。您应该使用此结构:

func retrieveScores(a: Int, b: Int) {

    var highScores: [Int]

    if a > 0 {
        if b > 0 {
            highScores = [1,1,1]
        }
    } else {
        highScores = [0,0,0]
    }

    for score in highScores {
        print(score)
    }
}

现在,编译器检测到没有实例化highScores的条件路径,因此它正确地抱怨它可能没有设置在您指定的位置。

请记住,编译器不会执行任何事情;它执行静态,即编译时,分析您的代码。即使失败的路径永远不会发生并且您知道,编译器也无法告诉!

如果您需要highScores是可选的,您仍然可以使代码安全:

var highScores: [Int]?

...

if let scores = highScores {
    for score in scores {
        print(score)
    }
} else {
    print("No scores found!")
}

一般建议:让编译器为您服务!您可以随意使用静态类型和类型检查;使用它们来避免尽可能多的运行时错误!