Reputation: 2113
extension CGPoint {
var coordx : String {
let xx = round(x * 10 * scaleFactor)/10 //No problem here
return "\(xx)"
}
var coordy : String {
let yy = round(y * 10 * scaleFactor)/10 //No problem here
return "\(yy)"
}
}
extension CGFloat {
var scaled : String {
let yy = round(self * 10 * scaleFactor)/10 //This generates an error.
return "\(yy)"
}
var scaled2 : String {
return CGPoint(x: self, y: self).coordx //No problem here
}
}
In the above code, I've marked with comments which lines work fine and which produces an error. There are three errors generated:
Cannot convert value of type '()' to expected argument type 'Int'
Cannot convert value of type 'CGFloat' to expected argument type 'FloatingPointRoundingRule'
Cannot use mutating member on immutable value: 'self' is immutable
Why would the CGPoint extension variables work fine but not the CGFloat extension? I notice with a right-click the y or x variables, I get a popup indicating the variable is a Double. Changing the extension to Double instead of CGFloat doesn't make a difference.
The components of a CGPoint are just CGFloats, so I'm confused why this doesn't work. I can use scaled2 as a workaround, but it seems absurd to make a CGPoint from a CGFloat just to get this to work.
The purpose of this code is to encode SVG output, which is done with strings. I'm sure there are other ways to accomplish this same task, but I'm trying to understand what's really going on here.
On other thing, when I option-click on the round
function that has an error, it says, possible match:
func round(FloatingPointRoundingRule)
If I option-click on the round
function of one of the ones that works, I instead get:
func round<T>(_ x: T) -> T where T : FloatingPoint
This suggests to me that the compiler has chosen a different round
function for the two scenarios. In an attempt to force one, I typed round( and waiting for the popup to show up, and then I selected it. That didn't help. Copy/pasting from one of the lines that works to the CGFloat
extension and then changing the variable also didn't work. So, what's going on her?
Upvotes: 0
Views: 66