[swift-evolution] [Discussion] Here we go again: Extension Functions

Stephen Celis stephen.celis at gmail.com
Mon Feb 29 08:04:24 CST 2016


> On Feb 29, 2016, at 7:33 AM, Radosław Pietruszewski <radexpl at gmail.com> wrote:
> 
> I have chills when I hear the idea of a closure changing the `self` from underneath me. JavaScript made me this way.
> 
> Of course, this is different than JavaScript, because it’s type-safe and you have to explicitly make a specific closure behave this way.
> 
> Still:
> - I fear that this can be awfully confusing because there’s no indication on call site that the closure has a different `self`.

Is this much different than the argument made against implicit vs. explicit `self` when calling methods and properties? Couldn't the context and editor make this fairly easy to disambiguate on the event that it _is_ confusing?

I agree that `with` presented problems in JavaScript (not just ambiguity, but forward-compatibility), and though `with` could be built rather easily in Swift using extension functions, it's not the core concept here (in any case, a protocol extension-based `then` would probably be preferred over `with`).

Ruby is another type-unsafe language with a community that heavily employs these kinds of DSLs via `instance_{eval,exec}`. The few issues I have with Ruby's system disappear with type safety and compile-time guarantees.

> - what if you do want to use your “outer self” inside the self-binding closure? Sure, in some cases, you could differentiate by `foo` and `self.foo`, but I suspect most self-binding closures would also be @noescape. And so, back to the JavaScript-like convention of `let this = self`? Ugh :(

In the past life I spent with Ruby, I don't ever remember fighting this, but in those rare cases that you want to refer to "outer" self, I don't see a prelude of `let value = self` or `let valueNeededForClosure = property` being a problem. Capture lists offer a shorthand:

    db.inTransaction { [name] in
        delete("users", "name = ?", [name])
    }

(While I believe it would be possible for the compiler to cascade to outer `self` methods and properties, I'm not convinced this is a good idea.)

> I do like that this syntax is not super noisy with all the $0’s, and also has the advantage that it doesn’t break when you only have a single expression (https://github.com/devxoul/Then#trouble-shooting). But maybe it’s not the way to go.

Was there an earlier version you preferred (see my long list at the beginning of this thread)? Do you have alternate ideas or ways to improve upon the idea of using extension functions?

Stephen



More information about the swift-evolution mailing list