[英]Swift array of generic closures?
Is it possible? 可能吗? The error
Only syntatic function types can be generic
suggests it isn't. 错误
Only syntatic function types can be generic
提示不是。
Valid Code 有效码
func test<T:Equatable>(function: (T) -> T){
var myArray:Array<T -> T> = [function];
}
Now I want to make a property with the same type as myArray
. 现在,我想创建一个与
myArray
类型相同的属性。 I feel like I should be able to do this somehow. 我觉得我应该能够以某种方式做到这一点。
Doesn't work 不起作用
var myArray:<T:Equatable>(T -> T)[]
Any ideas? 有任何想法吗?
Even this: 即使这样:
func test<T:Equatable>(function: (T) -> T){
var myArray:Array<T -> T> = function;
}
Shouldn't be valid. 无效。 You are assigning a
T->T
to a Array<T->T>
. 您正在将
T->T
分配给Array<T->T>
。 It should be at least: 至少应为:
var myArray:Array<T -> T> = [function];
This would work: 这将工作:
class MyClass<T> {
var myArray:(T->T)[] = []
}
Since you now have a generic MyClass class, to initialise, you need to tell what type T
is, like so: 由于您现在有了一个通用的MyClass类,因此要初始化,您需要知道
T
是什么类型,如下所示:
var x = MyClass<String>()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.