Swift 具有可以作为参数传递的一等函数。
func a() {
}
func b(x: ()) {
}
// Pass a to b…
b(a)
Swift 具有泛型函数。
func generic<T>(x: T) {
}
但是,Swift 允许我将一个通用函数作为参数传递给另一个函数吗?
let anIntService = Service<Int>()
let astringService = Service<String>()
func attach<T>(service: Service<T>, to value: T) {
// Perform type safe attaching of `value` to `service`.
}
func doAttaching(attach: (Service<T>, to T)->Void) {
attach(anIntService, to: 42)
attach(aStringService, to: "Hello World!")
}
doAttaching(attach)
…还是它只让我传递泛型函数的特定实例?
如果可能,请说明定义接受泛型函数作为参数的函数的语法。
如果不支持,解决方法是将泛型函数定义为结构的方法或其他方法,并传递 an 而不是它。但这并不理想,因为消费函数没有获得如此好的调用语法,他们需要这样做:
func doAttaching(attach: Attacher) {
attacher.attach(anIntService, to: 42)
attacher.attach(aStringService, to: "Hello World")
}
最佳答案
此功能通常称为 Higher-Kinded Types (HKT),目前在 Swift 中不受支持。
关于swift - swift 中的一等泛型函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37218873/