swift - swift 中的一等泛型函数?

标签 swift function generics first-class

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 中不受支持。

然而,它一直是discussed on the swift-evolution mailing list .

关于swift - swift 中的一等泛型函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37218873/

相关文章:

c - 使用 C/C++ 库进行 Swift 链接和构建

ios - 是否可以强制 iOS 设备以编程方式从所述应用程序打开/切换到我的应用程序?

c++ - 带有&符号的函数原型(prototype)是什么意思?

c++ - isupper() 是宏还是函数?

xcode - swift/Xcode6 : "found nil unwrapping optional" for my user's location

ios - sonar-swift 分析 xcode 项目

ios - 字典不允许我将字符串附加到它的值

c# - 如何实现通用的 OpenForm 方法以允许任何类型的表单

objective-c - block 中的 Objective C 泛型

delphi - 将泛型类型从一个类传递到另一个类时出错