简体   繁体   English

在Swift扩展中访问具有多个参数的方法

[英]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). 我有一种方法可以将一些值标准化到可用范围内(例如,从123-987到0-1)。

I want to create a reusable CGFloat exension of this. 我想为此创建可重用的CGFloat扩展。 The method accepts three parameters and returns a CGFloat as per the signature below. 该方法接受三个参数,并根据下面的签名返回CGFloat。 How can this be made into an extension of CGFloat so that I can store the result in a variable? 如何将其转换为CGFloat的扩展,以便将结果存储在变量中?

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: 您可以将range方法设为static ,然后将其调用为:

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

But another would be to remove the position parameter and use self . 但是另一个方法是删除position参数并使用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 也许您想使方法static

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

Then you can call it on CGFloat type itself 然后您可以在CGFloat类型本身上调用它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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