简体   繁体   English

Swift:将通用类型限制为闭包

[英]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 }
}

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM