我想实现一个 DSL,类似于 Kotlin 中的构建器:http://kotlinlang.org/docs/reference/type-safe-builders.html
这个想法是使用扩展方法作为函数参数,这样您就可以使用在给定参数的闭包中扩展的类中的方法。本质上允许您将方法和变量注入(inject)到闭包的范围中。
这在 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
的实例。它返回
实例方法 $0.head
作为类型 () -> ()
的函数。
关于ios - 如何在 Swift 中使用扩展方法作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32874727/