error: 'Int' is not convertible to '@lvalue Float'

白昼怎懂夜的黑 提交于 2019-12-05 12:19:17

If you start by changing the function to the following you get a more helpful error message:

func reduce() {
    let gcd = greatestCommonDenominator(numerator,denominator)
    self.numerator = self.numerator / gcd
    self.denominator = self.denominator / gcd
}

Now the error becomes:

error: cannot assign to 'numerator' in 'self'
        self.numerator = self.numerator / gcd
        ~~~~~~~~~~~~~~ ^

What may not be immediately obvious to those of us who are coming from Objective-C (or didn't RTFM) is that by default, functions in structs are not allowed to change the properties of a struct. You can get around this by explicitly declaring the function as a mutating function:

mutating func reduce() {
    let gcd = greatestCommonDenominator(numerator,denominator)
    self.numerator /= gcd
    self.denominator /= gcd
}

The mutating word solves both errors.

In the case of /=, the error is quite cryptic and unhelpful. I'll be filing a bug report and encourage others to do so as well.


EDIT: The real problem here has nothing to do with structs or compound assignment operators.

The problem here has to do with the fact that we're trying to assign to an rvalue that's unassignable. In the case of the struct, the rvalue was unassignable because the function was not declared as mutating. In the case of the let variable, it was unassignable because that's how let works. The error message is still misleading and confusing however. Rather than suggesting that there might be a type mismatch, the error should inform us that the rvalue is unassignable, just as it would if we tried to assign a const in Objective-C.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!