Swift:将泛型类型限制为闭包

时间:2015-07-23 08:24:15

标签: swift generics swift-protocols

如何将泛型类型限制为闭包? 像这样:

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

1 个答案:

答案 0 :(得分:3)

我不认为你可以 - 而是使用通用占位符来约束闭包的输入和返回参数,这相当于:

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>