【问题标题】:Wrapping functions包装函数
【发布时间】:2019-11-24 08:44:47
【问题描述】:

在 swift 函数中,不提供名义类型的常规功能。这意味着唯一的解决方案是将它们包装到某个对象中。在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'

有没有办法让它成为可能,还是由于类型系统设计缺陷而无法实现?

【问题讨论】:

  • @Chris Uhm,我不确定我是否理解您所指的代码。 op中的例子是完整的。我猜,你的意思是这个let a = Functor&lt;Int, Int&gt;.init { a in a + 1 }。即使我们将原始示例提取到这个 struct Functor&lt;Input, Output&gt; { //assuming only fuctions with one argument let function: (Input) -&gt; Output init&lt;Input, Output&gt;(_ function: @escaping (Input) -&gt; Output) { self.function = function //there is already a compilation error } } let myLovelyFunction = Functor&lt;Int, Int&gt;.init { a in return a + 1 } 它仍然会产生错误
  • 是的,我的错误 - 对不起!没有对上下文给予足够的关注。

标签: swift function generics types rtti


【解决方案1】:

当您在泛型类型中声明泛型方法时,内部泛型参数(在方法上)会影响外部泛型参数。

你不应该让你的初始化器通用:

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
    }
}

我不明白你真正想对第二个错误行做什么,所以请添加评论或更新你的问题以澄清这一点。

【讨论】:

  • 我想添加以下程序 ``` func hasSignature(identicalTo another: Self) -> Bool //(...) func hasArgumentSignature(identicalTo another: Self) -> Bool func hasSameReturnType(as另一个:自我)->布尔```
  • 我最后想要的是postconditionspreconditions,就像在 D lang 中一样。检查输入和输出是否满足给定的谓词。这就是我相信@CustomStorage(constarints: [{ $0 is Numeric }]) var someNumber: Any = 5; try? assign(value: 0.5, to: someNumber) 最终会带来的东西
  • @oneWayTicket,您最好在帖子中添加所有这些要求。泛型类型不会像您期望的那样工作。 Self 完全等同于专用类型。当fnFunctor&lt;Int, Int&gt; 时,hasSignature(identicalTo: 只接受(Int)-&gt;Int。 Swift 不是 D,处理动态类型的方式因语言而异。您可能需要重新设计策略以实现您真正想做的事情。更新您的问题并描述您真正想做的事情,然后有人可以向您展示 Swifty 设计将如何。
  • 好的,我会的。感谢您的回复。
猜你喜欢
  • 2017-11-30
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 2021-02-27
  • 2013-05-23
  • 2012-06-03
  • 2011-11-11
  • 2016-09-02
相关资源
最近更新 更多