I'm currently upgrading a forked Framework to Swift 3.
Working Swift 2 Code:
public extension CGFloat {
var roundToNearestHalf: CGFloat {
return round(self * 2)/2
}
}
In Swift 3, the return throws the compiler error : Cannot use mutating member on immutable value: 'self' is immutable
.
I was able to find tons of documentations why a method of a Struct need to to mutable. But so far I'm not able to find a solution for a variable.
If I enter the keyword mutating, the compiler throws the error: Expected declaration
public extension CGFloat {
var roundToNearestHalf: CGFloat mutating {
return round(self * 2)/2
}
}
My research on this issue is, that the code seems to be misplaced - so it needs to be within a function.
public extension CGFloat {
mutating func roundToNearestHalf() -> CGFloat {
var roundToNearestHalf: CGFloat {
return round(self * 2)/2
}
}
}
Now the compiler complains about the `*``
Research on that issue brought me to this Thread, that suggests to use the round
function the way I'm trying too.
Since this code obviously worked till Swift 3, I'd like to know why it does not anymore. Why does a var has to be declared as mutable now? And how do I need to declare the var roundToNearestHalf
now? Help is very appreciated.