简体   繁体   中英

Accessing a method with multiple paramaters in a Swift extension

I have a method to normalise some values into a usable range (eg 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?

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM