Saturday, June 15, 2024
HomeiOS Developmentios - Seeming inconsistency in Swift - why does this work with...

ios – Seeming inconsistency in Swift – why does this work with CGPoint however not with CGFloat?


extension CGPoint {
    var coordx : String {
        let xx = spherical(x * 10 * scaleFactor)/10   //No drawback right here
        return "(xx)"
    }

    var coordy : String {
        let yy = spherical(y * 10 * scaleFactor)/10   //No drawback right here
        return "(yy)"
    }
}

extension CGFloat {

    var scaled : String {
        let yy = spherical(self * 10 * scaleFactor)/10   //This generates an error.
        return "(yy)"
    }

    var scaled2 : String {
        return CGPoint(x: self, y: self).coordx   //No drawback right here
    }
}

Within the above code, I’ve marked with feedback which traces work high quality and which produces an error. There are three errors generated:

Can't convert worth of sort '()' to anticipated argument sort 'Int'
Can't convert worth of sort 'CGFloat' to anticipated argument sort 'FloatingPointRoundingRule'
Can't use mutating member on immutable worth: 'self' is immutable

Why would the CGPoint extension variables work high quality however not the CGFloat extension? I discover with a right-click the y or x variables, I get a popup indicating the variable is a Double. Altering the extension to Double as an alternative of CGFloat does not make a distinction.

The parts of a CGPoint are simply CGFloats, so I am confused why this does not work. I can use scaled2 as a workaround, nevertheless it appears absurd to make a CGPoint from a CGFloat simply to get this to work.

The aim of this code is to encode SVG output, which is finished with strings. I am certain there are different methods to perform this similar process, however I am making an attempt to grasp what’s actually occurring right here.

On different factor, once I option-click on the spherical perform that has an error, it says, doable match:

func spherical(FloatingPointRoundingRule) 

If I option-click on the spherical perform of one of many ones that works, I as an alternative get:

func spherical<T>(_ x: T) -> T the place T : FloatingPoint

This means to me that the compiler has chosen a special spherical perform for the 2 eventualities. In an try and pressure one, I typed spherical( and ready for the popup to indicate up, after which I chosen it. That did not assist. Copy/pasting from one of many traces that works to the CGFloat extension after which altering the variable additionally did not work. So, what is going on on her?



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments