Literphor
Literphor

Reputation: 498

Swift array of generic closures?

Is it possible? The error Only syntatic function types can be generic suggests it isn't.

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. I feel like I should be able to do this somehow.

Doesn't work

var myArray:<T:Equatable>(T -> T)[]

Any ideas?

Upvotes: 1

Views: 2796

Answers (1)

Rui Peres
Rui Peres

Reputation: 25917

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>. 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:

var x = MyClass<String>()

Upvotes: 4

Related Questions