Swift 4-表达式类型'@lvalue String?'没有更多的上下文是模棱两可的

时间:2018-10-04 21:34:01

标签: xcode swift4

我正在尝试在自己正在做的游戏中记录得分和高分。但是我一直收到这个错误:

enter image description here

有关如何解决此问题的任何线索?我有Xcode 10,并且正在使用Swift4。在此先感谢!

import UIKit
import Foundation

class ScoreVC: UIViewController {
    @IBOutlet weak var scoreLabel: UILabel!
    @IBOutlet weak var highscoreLabel: UILabel!

    @IBOutlet weak var reset: UIButton!
    @IBOutlet weak var points: UIButton!

    var Score = 0
    var Highscore = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        let HighscoreDefault = UserDefaults.standard

        if (HighscoreDefault.value(forKey: "Highscore") != nil) {
            Highscore = HighscoreDefault.value(forKey: "Highscore") as! Int
            highscoreLabel.text = NSString(format: "Highscore: %i", Highscore) as String
        }
    }

    @IBAction func resetButton(_ sender: Any) {
        Score = 0
        scoreLabel.text = NSString(format: "Score: %i", Score) as String
    }

    @IBAction func pointsButton(_ sender: Any) {
        Score +=
        scoreLabel.text = NSString(format: "Score: %i", Score) as String
        if (Score > Highscore) {
            Highscore = Score
            highscoreLabel.text = NSString(format: "Highscore: %i", Highscore) as String

            var HighscoreDefault = UserDefaults.standard
            HighscoreDefault.setValue(Highscore, forKey: "Highscore")
            HighscoreDefault.synchronize()
        }
    }
}

2 个答案:

答案 0 :(得分:3)

从pointsButton编辑此行:

 guard let scoreLabel = scoreLabel.text else {
            return
        }

答案 1 :(得分:0)

pointsButton编辑此行:

Score += 1

关于错误消息,

scoreLabel.text = NSString(format: "Score: %i", Score) as String

此处scoreLabel.text左值,因为它位于赋值运算符=的左侧。在前面的行中,在您的原始代码中,Score +=期望 rvalue ,并且赋值操作不能被视为rvalue。