[swift-evolution] Idea for enabling DSLs: bind to self in closures

Stephen Celis stephen.celis at gmail.com
Fri Dec 4 16:35:12 CST 2015


On Fri, Dec 4, 2015 at 4:44 PM, David Waite <david at alkaline-solutions.com>
wrote:

>
> All of the matching methods (such as equal, contains, raiseError,
> raiseException) are also module functions, so you would likely just pull
> them all in. The Hamcrest Java project is very similar to Nimble, and they
> have a utility class generator (static methods calling other class static
> methods) specifically for reducing the number of static imports you have to
> put at the top of your test files.
>

They don't need to be, though. Protocol extensions offer an improved way of
handling this. I put together a proof-of-concept PR a short while ago:

https://github.com/Quick/Nimble/pull/218


> Ruby has it as well, and while it perhaps a bit more ‘magic’ than some
> would desire, you will not find Ruby developers lamenting its existence.
> Javascript’s inconsistent historical behaviors greatly contribute to the
> perception that rebinding is a design flaw.
>

The Ruby community in the past has been somewhat divided on the use of
instance_eval/exec vs. yielding block arguments for clarity, though there
are many popular DSL-like libraries that take advantage of
instance_eval/exec and are expressive and easy to read at the cost of
opaqueness.


> However, the behavior I’m describing is different than either Ruby or
> Javascript:
> - both Ruby and Javascript are late bound, which allows the JIT
> implementations to adapt to whatever type instance is given. Swift is not a
> late bound language, so it must know the types it is working with beforehand
> ...
>

Perhaps a bracketed annotation could assign an unbound type to a closure:

    let builder: [MyType] () -> Void = { ... }
    builder.bind(instance)() // or builder[instance](), or some other syntax

I agree that such a mechanism would allow for very expressive, type-safe
APIs. IDEs could take the guesswork out of "what is 'self'?". At the same
time, I understand apprehensions and aversions to both the complexity and
ambiguities associated with such a feature, and they may go against Swift's
principles at the moment.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151204/881363e1/attachment.html>


More information about the swift-evolution mailing list