如何在Swift中使用扩展方法作为参数?

我想实现一个类似于他们可以在Kotlin中使用构建器的DSL: http : //kotlinlang.org/docs/reference/type-safe-builders.html

这个想法是使用扩展方法作为函数参数,以便您可以使用在您给出参数的闭包中扩展的类中的方法。 本质上允许您将方法和变量注入到闭包的范围中。

在Swift中似乎几乎是可能的,但也许我错过了一些东西。 下面的代码工作,直到我试图在闭包内调用head()

 // Class with method to be available within closure class HTML { func head() { print("head") } } // Create a type with same signature as an extension method typealias ext_method = HTML -> () -> () func html(op: ext_method) { let html = HTML() op(html)() // call the extension method } html { head() // ! Use of unresolved identifier 'head' } 

有没有人有任何运气做类似的事情,或有一个想法,如何可能?

我不知道这是你在找什么,但是

 html { $0.head } 

会编译并似乎产生预期的输出。

闭包接受一个参数(这里使用简写参数名称$0 ),它是HTML一个实例。 它作为type () -> ()的函数返回实例方法$0.head

Interesting Posts