Search code examples
swiftcgfloat

Accessing a method with multiple paramaters in a Swift extension


I have a method to normalise some values into a usable range (e.g. from 123-987 to 0-1).

I want to create a reusable CGFloat exension of this. The method accepts three parameters and returns a CGFloat as per the signature below. How can this be made into an extension of CGFloat so that I can store the result in a variable?

func range(position: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat {
    //
}

A working example is as below, but this seems like the wrong thing to do.

extension CGFloat {
    func range(position: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat {
        //
    }
}
let float: CGFLoat = 0 // This seems needless, but I can't see another way of accessing the method
let result = float.range(position: 200, min: 123, max: 987)

Any suggestions on how to write this correctly?


Solution

  • You can make the range method static and then call it as:

    let result = CGFloat.range(position: 200, min: 123, max: 987)
    

    But another would be to remove the position parameter and use self.

    extension CGFloat {
        func range(min: CGFloat, max: CGFloat) -> CGFloat {
            // ensure self is normalized to the range and return the updated value
        }
    }
    
    let someFloat: CGFloat = 200
    let result = someFloat.range(min: 123, max: 987)