4

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")
}
4

3 回答 3

4

此功能通常称为高级类型(HKT),目前 Swift 不支持。

但是,它已在 swift-evolution 邮件列表中进行了讨论

于 2016-05-13T23:53:31.623 回答
0

是的,这是一个例子:

func identity<T>(param: T) -> T {
    return param
}

func callFunction<U>(function: U->U, paramater: U) -> U {
    return function(paramater)
}

let param = 123

let result = callFunction(identity, paramater: param);

print(result)

(你可以在这里运行)

于 2016-05-13T20:41:03.217 回答
0

我意识到,在问了这个问题五年后,Swift 支持了一些类似这样的东西,它可以通过callAsFunction.

这是一个例子:


final class Service<T> {
    // Implementation here
}

final class Attacher {
    // Important state here.
    var state = Void()
    
    func callAsFunction<T>(service: Service<T>, to: T) {
        // Implementation here.
    }
}

func doAttaching(attach: Attacher) {
    attach(service: Service<Int>(), to: 42)
    attach(service: Service<String>(), to: "Hello World!")
}

ARepeater可以传递给通用代​​码并提供有用的行为。

于 2022-01-13T09:14:30.557 回答