0

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?

2 Answers2

2

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)
rmaddy
  • 314,917
  • 42
  • 532
  • 579
1

Maybe you want to make your method static

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

Then you can call it on CGFloat type itself

let result = CGFloat.range(position: 200, min: 123, max: 987)
Robert Dresler
  • 10,580
  • 2
  • 22
  • 40