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

标签 ios swift swift2

我想实现一个 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/

相关文章:

ios swift 3 为自定义键盘构建底部标签栏

ios - FBSDKAppInviteDialog 不加载好友列表

ios - 如何绘制一个里面有数字/字符串的圆盘?

swift - 如何快速重新加载打开的标签栏

ios - GMSAutocompleteViewController iOS,如何更改搜索栏中的文本颜色

ios - 手势关闭键盘后,TableView 点击失败

ios - PDF 图像格式无法在 iOS 中以编程方式使用 swift 工作

ios - 在主包中搜索 XIB

ios - 添加到 MKMapView 时出现 UILongPressGestureRecognizer 问题

Swift tvOS 应用内购买没有响应