user3774327
user3774327

Reputation: 76

Swift: restrict generic type to closure

How can I restrict generic type to closures? Like this:

struct Closure<T where T:closure> {
  var closure:T
  init(_ c:T) { closure = c }
}

Upvotes: 2

Views: 352

Answers (1)

Airspeed Velocity
Airspeed Velocity

Reputation: 40955

I don’t think you can – instead, use generic placeholders to constrain the input and return arguments of the closure, which amounts to the same thing:

struct Closure<T,U> {
    var closure: T->U
    init(_ c: T->U) { closure = c }
}

let c = Closure { $0 % 2 == 0 }
// c will be a Closure<Int,Bool>

Upvotes: 3

Related Questions