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

时间:2022-09-23 08:05:01

I would like to implement a DSL similar to what they can do with builders in Kotlin: http://kotlinlang.org/docs/reference/type-safe-builders.html

我想在Kotlin中实现类似于他们可以对建设者做的DSL:http://kotlinlang.org/docs/reference/type-safe-builders.html

The idea is use extension methods as function arguments, so that you can use methods from the class being extended within the closure you give a argument. Essentially allowing you to inject methods and variables into the scope of the closure.

这个想法是使用扩展方法作为函数参数,这样你就可以使用在你提供参数的闭包中扩展的类中的方法。基本上允许您将方法和变量注入闭包的范围。

It seems to be almost possible in Swift, but maybe I am missing something. The following code works, right until I try to call head() within the closure:

在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'  
}

Have anyone had any luck doing something similar, or have an idea to how it would be possible?

有没有人有运气做类似的事情,或者知道如何做到这一点?

1 个解决方案

#1


0  

I have no idea if this is what you are looking for, but

我不知道这是不是你想要的,但是

html {
    $0.head  
}

would compile and seems to produce the expected output.

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

The closure takes a single parameter (here using the shorthand parameter name $0) which is an instance of HTML. It returns the instance method $0.head as a function of type () -> ().

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

#1


0  

I have no idea if this is what you are looking for, but

我不知道这是不是你想要的,但是

html {
    $0.head  
}

would compile and seems to produce the expected output.

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

The closure takes a single parameter (here using the shorthand parameter name $0) which is an instance of HTML. It returns the instance method $0.head as a function of type () -> ().

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