包装功能

时间:2019-11-24 08:44:47

标签: swift function generics types rtti

在快速函数中,不能提供名义类型的常规功能。这意味着唯一的解决方案是将它们包装到某个对象中。在struct中,例如:

struct Functor<Input, Output> {
    //assuming only fuctions with one argument
    let function: (Input) -> Output
    let inputType: Input.Type
    let outputType: Output.Type
    let input: Input
    let output: Output

    init<Input, Output>(_ function: @escaping (Input) -> Output) {
        self.function = function //there is already a compilation error
        self.input = Input //???? And I have not a clue on how to store argument as instance
    }
}

编译器说:

error: cannot assign value of type '(Input) -> Output' to type '(Input) -> Output'

有没有办法使之成为可能,或者由于类型系统设计的缺陷而无法实现?

1 个答案:

答案 0 :(得分:2)

在泛型类型中声明泛型方法时,内部泛型参数(在方法上)会遮盖外部泛型参数。

您不应使初始化程序通用:

struct Functor<Input, Output> {
    //assuming only fuctions with one argument
    let function: (Input) -> Output
    let inputType: Input.Type
    let outputType: Output.Type
    //### I do not understand how you want to use the followings...
//    let input: Input
//    let output: Output

    init(_ function: @escaping (Input) -> Output) { //### Do not put inner generic parameters
        self.function = function
        //### I do not understand how you want to use the followings...
        self.inputType = Input.self
        self.outputType = Output.self
    }
}

我不明白您对第二个错误行的真正想法,因此请添加注释或更新您的问题以澄清这一点。