二元运算符 += 不能应用于两个 Int 操作数

binary operator += cannot be applied to two Int operands

我正在创建一个简单的结构。

struct Expenses {

    var totalExpenses:Int = 0

    func addExpense(expense: Int) {
        totalExpenses += expense
    }
}

它在行首产生错误 totalExpenses += expense 错误信息是

binary operator += cannot be applied to two Int operands.

为什么我会收到错误消息以及如何解决这个问题?

您需要指定 addExpense 是一个 mutating 函数,如下所示:

struct Expenses {
    var totalExpenses:Int = 0

    mutating func addExpense(expense: Int) {
        totalExpenses += expense
    }
}

来自文档:

Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.

However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method.

有关详细信息,请参阅 The Swift Programming Language: Methods

除非使用 mutating 关键字,否则无法更改结构,默认情况下结构不可变,试试这个:

mutating func addExpense(expense: Int) { ... }

前几天我遇到了这个问题,要么在你的函数上使用 mutating 关键字,要么将你的 struct 定义为 class