为什么以下快速代码给我带来错误“一元运算符'++'无法应用于类型为'Int'的操作数”的错误? (在Xcode-6.3.2上使用swift-1.2)

struct Set {

    var player1Games: Int
    var player2Games: Int

    init() {
        self.player1Games = 0
        self.player2Games = 0
    }

    func increasePlayer1GameScore () {
        player1Games++   // error: Unary operator '++' cannot be applied to an operand of type 'Int'
    }

    func increasePlayer2GameScore () {
        player2Games++   // error: Unary operator '++' cannot be applied to an operand of type 'Int'
    }

}

最佳答案

该错误消息有点误导。您需要做的是mutating之前添加func以指定它将modify该结构:

struct MySet {

    var player1Games: Int
    var player2Games: Int

    init() {
        self.player1Games = 0
        self.player2Games = 0
    }

    mutating func increasePlayer1GameScore() {
        player1Games++
    }

    mutating func increasePlayer2GameScore() {
        player2Games++
    }

}

注意:Set是Swift中的一种类型,我建议为您的结构使用一个不同的名称。

10-02 23:39