2015-09-30 30 views
0

我想实现类似,他们可以在科特林与建筑工地做什么DSL:http://kotlinlang.org/docs/reference/type-safe-builders.html如何在Swift中使用扩展方法作为参数?

的想法是使用扩展方法作为函数的参数,这样就可以使用来自类的方法关闭之内被延长你给出一个论点。基本上允许你将方法和变量注入闭包的范围。

它似乎是差不多可能在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' 
} 

有任何人任何运气做类似的东西,或有一个想法,怎么会是可能的?

+1

您可能会提到这也发布在Apple Developer Forum上:https://forums.developer.apple.com/thread/20481。 –

+0

请原谅我的无知,但在这种情况下,DSL *是什么? –

+0

@MartinR域特定语言https://en.wikipedia.org/wiki/Domain-specific_language – matt

回答

0

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

html { 
    $0.head 
} 

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

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

+0

我正在寻找的是一种避免最初的$ 0。扩展方法的一个关键特性是它们可以直接访问它们扩展的类中的方法,但是当用作闭包时,该功能似乎会丢失。 – ast

+0

@ast:闭包不在HTML类或扩展声明的范围内,所以* I *看不到如何实现这一点。也许别人会...... –

相关问题