【发布时间】: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<Int, Int>.init { a in a + 1 }。即使我们将原始示例提取到这个struct Functor<Input, Output> { //assuming only fuctions with one argument let function: (Input) -> Output init<Input, Output>(_ function: @escaping (Input) -> Output) { self.function = function //there is already a compilation error } } let myLovelyFunction = Functor<Int, Int>.init { a in return a + 1 }它仍然会产生错误 -
是的,我的错误 - 对不起!没有对上下文给予足够的关注。
标签: swift function generics types rtti